[leetcode]415. Add Strings字符串相加

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

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. 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 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9823953.html
今日推荐