Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
题目大意:
给定两个非负整数,用字符串表示。计算两个整数的和。
理 解:
涉及到大数求和。从两个字符串最后一位开始往前遍历,存在进位则flag= 1,同时当前位sum = sum-10。
注意计算的是两个字符的和,转换为十进制数字,需要在字符的基础上减48.因为字符'0'对应的ASCII码为48.
方法二效率很高。使用string迭代器,reverse等。且灵活取余、取模。
代 码 C++:
方法一:
class Solution {public: string addStrings(string num1, string num2) { string res=""; int len1,len2; len1 = num1.length(); len2 = num2.length(); int i=len1-1,j=len2-1,flag=0,sum=0; // flag判断是否存在进位 //cout<<<" "<< =0&&j>=0){ sum = num1[i]+num2[j]+flag - 96; // cout< <<" "< < 9){ flag = 1; sum = sum -10; }else{ flag = 0; } res = to_string(sum) + res; // cout< < =0){ sum = num1[i] + flag - 48; if(sum>9){ flag = 1; sum = sum -10; }else{ flag = 0; } res = to_string(sum) + res; i--; } while(j>=0){ sum = num2[j] + flag - 48; if(sum>9){ flag = 1; sum = sum -10; }else{ flag = 0; } res = to_string(sum) + res; j--; } if(flag==1) res = "1" + res; return res; }};
方法二:
class Solution {public: string addStrings(string num1, string num2) { auto itr1 = num1.rbegin(),itr2 = num2.rbegin(); int carry = 0,sum; string res; while(carry || itr1!=num1.rend() || itr2!=num2.rend()){ sum = carry; if(itr1!=num1.rend()){ sum += *itr1 - '0'; itr1++; } if(itr2!=num2.rend()){ sum += *itr2 - '0'; itr2++; } carry = sum/10; res.push_back(sum%10 + '0'); } reverse(res.begin(),res.end()); return res; }};
运行结果:
方法一:
执行用时 :48 ms, 在所有 C++ 提交中击败了22.57%的用户
内存消耗 :58.1 MB, 在所有 C++ 提交中击败了12.82%的用户
方法二:
执行用时 :8 ms, 在所有 C++ 提交中击败了93.58%的用户
内存消耗 :9 MB, 在所有 C++ 提交中击败了81.48%的用户