LintCode :Big Integer Addition

来源:互联网 发布:mac vpn推荐 编辑:程序博客网 时间:2024/06/04 08:41

描述:

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.


注意事项
  • 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.

样例

Given num1 = "123", num2 = "45"
return "168"


class Solution {public:/*** @param num1 a non-negative integers* @param num2 a non-negative integers* @return return sum of num1 and num2*/string addStrings(string& num1, string& num2) {// Write your code hereint add_bit = 0, i = 0;char temp, result[6100] = { 0 };const char *n1 = num1.c_str();const char *n2 = num2.c_str();int len1 = strlen(n1);int len2 = strlen(n2);while (len1 != 0 && len2 != 0) {len1--; len2--;result[i] = (add_bit + n2[len2] + n1[len1] - 2 * '0') % 10 + '0';add_bit = (n2[len2] + n1[len1] + add_bit - '0' * 2) / 10;i++;}if (len1 > len2) {while (len1) {len1--;result[i] = (add_bit + n1[len1] - '0') % 10 + '0';add_bit = (n1[len1] + add_bit - '0') / 10;i++;}}else {while (len2) {len2--;result[i] = (add_bit + n2[len2] + add_bit- '0') % 10 + '0';add_bit = (add_bit + n2[len2] - '0') / 10;i++;}}if (add_bit) {result[i] = '1';i++;}for (int j = 0; j < i / 2; j++){temp = result[j];result[j] = result[i - 1 - j];result[i - 1 - j] = temp;}result[i] = '\0';return result;}};