Problem:
Given non-negative numbers num1
num2
and represented as String, return the sum of num1
num2
.
- The length of both and is
num1
num2
< 5100.
- Both
num1
and num2
contains only digits 0-9
.
- Both
num1
and num2
does not contain any leading zero.
- You must no built-in BigInteger library or convert the inputs to integer directly.
Summary:
The addition of two shaped numbers in the form of a string.
Analysis:
This problem is a regular problem, it is not difficult, just one person to add, pay attention to carry in the time with a carry.
1 classSolution {2 Public:3 stringAddStrings (stringNUM1,stringnum2) {4 intLen1 = Num1.size (), len2 =num2.size ();5 inti = len1-1, j = len2-1, k =0, carry =0;6 Charres[5200];7 8 while(I >=0&& J >=0) {9 intsum = Num1[i] + num2[j]-2*'0'+carry;Ten if(Sum >9) { OneSum-=Ten; Acarry =1; - } - Else { thecarry =0; - } - -res[k++] = sum +'0'; +i--; j--; - } + A while(I >=0) { at intsum = Num1[i] + carry-'0'; - if(Sum >9) { -Sum-=Ten; -carry =1; - } - Else { incarry =0; - } to +res[k++] = sum +'0'; -i--; the } * $ while(J >=0) {Panax Notoginseng intsum = Num2[j] + carry-'0'; - if(Sum >9) { theSum-=Ten; +carry =1; A } the Else { +carry =0; - } $ $res[k++] = sum +'0'; -j--; - } the - if(carry) {Wuyires[k++] ='1'; the } - Wures[k++] =' /'; - About for(i =0; I < K/2; i++) { $ CharTMP =Res[i]; -Res[i] = res[k-i-2]; -Res[k-i-2] =tmp; - } A + stringResstr =string(res); the - returnResstr; $ } the};
The above for me to write the original code, the code is too lengthy, the following is a reference to the online Daniel code optimization code, a lot of code introduction:
1 classSolution {2 Public:3 stringAddStrings (stringNUM1,stringnum2) {4 intLen1 = Num1.size (), len2 =num2.size ();5 inti = len1-1, j = len2-1, carry =0;6 stringres ="";7 8 while(I >=0|| J >=0) {9 intSUM1 = i >=0? num1[i--]-'0':0;Ten intsum2 = J >=0? num2[j--]-'0':0; One A intsum = sum1 + sum2 +carry; -Res.insert (Res.begin (), Sum%Ten+'0'); -carry = SUM/Ten; the } - - returnCarry?"1"+Res:res; - } +};
Leetcode 415 Add Strings