Subtract large numbers (String)

Hello guys ,

I’m stuck here in the subtraction. i did for MULTIPLICATION AND ADDITION. But god knows whats with the subtraction.

I want to Subtract two number that are stored in STRING.(Efficient Way )

e.g

string num1= "1233443267532847324324234234325454353";
string num2= "3842364753245832443534543534534";
string result;

//Parsing and all stuff

Sorry to ask this here But i really need some help here.

It’s exactly the same as the way you did it in kindergarten. You need a for loop that starts from the right most digit, subtract a digit at a time, “borrow ten” from the next column over if you need to, etc. If you just want code, do some Google searching.

void Subtract ()
{

				int borrow = 0;
				int difference = 0;
				int digit_1 = 0;
				int digit_2 = 0;
				int k = 0;
				char[] num1Char = num1.ToCharArray ();
				char[] num2Char = num2.ToCharArray ();
				int[] resultChar = new int[num1Char.Length];

//				Array.Reverse (num1Char);
//				Array.Reverse (num2Char);

				int length1 = num1Char.Length;
				int length2 = num2Char.Length;

				for (int i=length1-1; i>=0; i--) {
						
						//This works because each character is internally represented by a number. 
						//The characters '0' to '9' are represented by consecutive numbers,
						//so finding the difference between the characters '0' and '2' results in the number 2.
						digit_1 = num1Char  *- '0';*
  •  				if (k > length2 - 1)*
    
  •  						digit_2 = 0;*
    
  •  				else*
    
  •  						digit_2 = num2Char [length2 - 1 - k] - '0';*
    
  •  				difference = (digit_1 - digit_2 - borrow);	*
    
  •  				if (difference < 0) {*
    
  •  						difference += 10;*
    
  •  						borrow = 1;*
    
  •  				} else*
    
  •  						borrow = 0;*
    
  •  				k++;*
    

_ resultChar = difference;_
* }*

* for (int i=0; i<length1; i++)*
_ result.Append (resultChar ); //result = new StringBuilder ();_

* Debug.Log (result);*
* }*
I know Its a bit of mess …But i did it … :wink: