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.
题目
如题
思路
1. while loop will run as long as there is character left in nums1, nums2 or carry
2. from right to left, each character is converted to integer
3. If the shorter string is exhausted first, the value will be forced to `0` as default
代码
1 class Solution { 2 public String addStrings(String num1, String num2) { 3 //how many digits will be added? three! 1st from num1Array, 2nd from num2Array, 3rd from carry 4 int carry = 0; 5 int num1Len = num1.length()-1; 6 int num2Len = num2.length()-1; 7 8 // StringBuilder can append and remove, more efficient 9 StringBuilder sb = new StringBuilder(); 10 11 //while loop will run as long as there is character left in nums1, nums2 or carry 12 while(num1Len >= 0 || num2Len >=0 || carry >0){ 13 // from right to left, each character is converted to integer 14 // If the shorter string is exhausted first, the value will be forced to `0` as default 15 int update1 = num1Len>=0 ? num1.charAt(num1Len--)-'0' :0; 16 int update2 = num2Len>=0 ? num2.charAt(num2Len--)-'0' :0; 17 int sum = update1 + update2 + carry; 18 sb.insert(0,sum%10); 19 carry = sum/10; 20 } 21 return sb.toString(); 22 } 23 }