首页 > 代码库 > 415. Add Strings

415. Add Strings

BitInteger的最简单的部分

把两个string反过来,从后往前加,可以学习的地方是对于while的条件可以设置成,index1< len1 || index2 < len2.

然后在内部分别对index1 < len1和index2 <len2处理,这样就不用对其中一个提前结束的情况单独再写一个循环了

 

 1     public String addStrings(String num1, String num2) {
 2         if(num1 == null) {
 3             return num2;
 4         }
 5         if(num2 == null) {
 6             return num1;
 7         }
 8         StringBuilder sb1 = new StringBuilder(num1);
 9         StringBuilder sb2 = new StringBuilder(num2);
10         int len1 = num1.length();
11         int len2 = num2.length();
12         sb1.reverse();
13         sb2.reverse();
14         StringBuilder sb = new StringBuilder();
15         int index1 = 0;
16         int index2 = 0;
17         int carry = 0;
18         while(index1 < len1 || index2 < len2) {
19             int cur = carry;
20             if(index1 < len1) {
21                 cur += sb1.charAt(index1++) - ‘0‘;
22             }
23             if(index2 < len2) {
24                 cur += sb2.charAt(index2++) - ‘0‘;
25             }
26             if(cur > 9) {
27                 cur %= 10;
28                 carry = 1;
29             } else {
30                 carry = 0;
31             }
32             sb.append(cur);
33         }
34         if(carry == 1) {
35             sb.append(1);
36         }
37         return sb.reverse().toString();
38     }

 

415. Add Strings