将两个大数字加为字符串

时间:2018-10-27 10:18:30

标签: c arrays char type-conversion ansi

我没有在此处添加“真实”代码片段,因为我尝试了多种变体(但均获得了成功),因此我将使用类似C的伪代码。

===

我想添加两个超过ANSI C最大的long long的数字(例如两个50位数字)

这个想法是,我将使用两个char[]数组,并通过将两个加数的每个字符转换为int,加法并携带十进制,然后分配结果来进行经典的笔纸风格加法再次作为charchar[]数组。

我遇到的问题是将char转换为int(总是失败)...然后将结果添加到另一个文本数组中。尝试使用char result[]或什至其ascii值result[i] = "5"result[i] = 53添加字符总是失败。

伪代码

int add(char *n1, char *n2){
    // examples (Intentionally not the same length)
    // n1     = "12345678901234567890"
    // n2     =      "987654321098765"
    char result[100]; // array for resulting added ints as char
    int r = 100; // The index (set to end) for the result array 
    result[r] = 0; // Assign the char-halt to END of the result
    int carry = 0; //  for carrying the 10s
    maxlength = <length of largest addend> // (sizeof(n)/sizeof(n[0])) doesnt work because pointers

    // start at end (right end) of arrays and move towards start (left end)
    // each loop takes one character, starting at the far RIGHT (end) of the string array
    // i = (maxlength - 1) to skip stop "0"
    for (int i = (maxlength - 1); i >= 0; i--) { 
        a1 = int()n1[i] // doesnt return correct value in tests. Neither does a1 = n1[i]-0
        a2 = int()n1[i] // doesnt return correct value in tests. Neither does a1 = n1[i]-0
        int asum = a1 + a2 + carry

        // carry all the tens
        carry = 0; // reset carry
        while (asum > 10){
            carry += 10; 
            asum -= 10; 
        }
        result[r] = char()asum 
        r -= 1 // Move result index one to the LEFT
    }
}    

1 个答案:

答案 0 :(得分:3)

  

我遇到的问题是将char转换为int ...

C标准保证'0''9'的10个字符连续保持并增加值:

  

5.2.1 Character sets

     

[...]

     

3基本源字符集和基本执行字符集均应具有以下成员:   10个十进制数字

     

0 1 2 3 4 5 6 7 8 9

     

[...]上面的十进制数字列表中的每个0后面的字符的值应比前一个的值大一个。

看看这个并得到一个概念:

#include stdio.h>

int main(void)
{
  char c = '7'; 
  int i = c - '0'; 

  printf("c = %c, i = %d\n", c, i); 
}