Subtract numbers using arrays - C++

纵然是瞬间 提交于 2019-12-08 09:30:53

问题


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 v and n (=q in the code)
  • vArray[i] = ith digit of v except leading zeros to fill the whole array
  • nArray[i] = - ith 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]

回答1:


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 (a.k.a. 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



来源:https://stackoverflow.com/questions/15006080/subtract-numbers-using-arrays-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!