Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Notice
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example
Given num1 = "123"
, num2 = "45"
return "168"
解法一:
1 class Solution { 2 public: 3 /** 4 * @param num1 a non-negative integers 5 * @param num2 a non-negative integers 6 * @return return sum of num1 and num2 7 */ 8 string addStrings(string& num1, string& num2) { 9 // Write your code here 10 int add_bit = 0, i = 0; 11 char temp, result[6100] = { 0 }; 12 const char *n1 = num1.c_str(); 13 const char *n2 = num2.c_str(); 14 int len1 = strlen(n1); 15 int len2 = strlen(n2); 16 while (len1 != 0 && len2 != 0) { 17 len1--; len2--; 18 result[i] = (add_bit + n2[len2] + n1[len1] - 2 * '0') % 10 + '0'; 19 add_bit = (n2[len2] + n1[len1] + add_bit - '0' * 2) / 10; 20 i++; 21 } 22 if (len1 > len2) { 23 while (len1) { 24 len1--; 25 result[i] = (add_bit + n1[len1] - '0') % 10 + '0'; 26 add_bit = (n1[len1] + add_bit - '0') / 10; 27 i++; 28 } 29 } 30 else { 31 while (len2) { 32 len2--; 33 result[i] = (add_bit + n2[len2] + add_bit- '0') % 10 + '0'; 34 add_bit = (add_bit + n2[len2] - '0') / 10; 35 i++; 36 } 37 } 38 if (add_bit) { 39 result[i] = '1'; 40 i++; 41 } 42 for (int j = 0; j < i / 2; j++) 43 { 44 temp = result[j]; 45 result[j] = result[i - 1 - j]; 46 result[i - 1 - j] = temp; 47 } 48 result[i] = '