I want to calculate the difference between two numbers (let's say v
and n
, so vn
) using arrays (don't ask why I have to do so). The arrays for each number are made in the following way:
v
and n
(= q
in the code) vArray[i]
= i
th digit of v
except leading zeros to fill the whole array nArray[i]
= - i
th digit of n
except 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]
I believe I understand the data structure, as you are using a Big Integer representation.
Given the number: 1234
Your V array is: [1, 2, 3, 4].
To add all the digits (aka sum), which I don't see why you want to do this, is:
int digit_sum = 0;
for (int i = 0; i < 4; i++)
{
digit_sum += v[i];
}
To convert the representation into "normal", try this:
int value = 0;
for (int i = 0; i < 4; ++i)
{
value = (value * 10) + v[i];
}
To perform a subtraction, you will have to perform the steps as if you doing this by hand. Also, you would need a second number too.
Edit 1: link to big number subtraction
This might help:
Big Number Subtraction in C
C++ Large Number Arithmetic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.