I want to calculate the difference between two numbers (let's say v and n, so v-n) using arrays (don't ask why I have to do so). The arrays for each number are made in the following way:
- Their capacity is the number of digits of the greatest number between
vandn(=qin the code) vArray[i]=ith digit ofvexcept leading zeros to fill the whole arraynArray[i]= -ith digit ofnexcept leading zeros to fill the whole array
For example, choose v = 10 and n = 2 then,
vArray = [1,0]
nArray = [0,-2]
So I wrote this code to calculate the sum array that will be equal to the digits of the difference (sum = [0,9] for the example above):
long r = 0;
for (int i = q-1 ; i > -1; i--){
sum[i] = vArray[i] + nArray[i];
if (sum[i] < 0){
r = floor(sum[i]/10);
sum[i-1] -= r;
sum[i] = sum[i]+10;
}else{
r = 0;
}
NSLog(@"%li",sum[i]);
}
The problem is that sum array isn't equal to what it should be. For the same example, sum = [1,8] What is the problem in the code?
note : vArray and nArray are properly generated.
EDIT : A few examples and expected results
v = | n = | vArray = | nArray= | sum=
25 | 9 | [2,5] | [0,9] | [1,6]
105 | 10 | [1,0,5] | [0,1,0] | [0,9,5]
1956 | 132 | [1,9,5,6] | [0,1,3,2] | [1,8,2,4]
369375 | 6593 |[3,6,9,3,7,5]| [0,0,6,5,9,3] |[3,6,2,7,8,2]