首页 > 其他 > 详细

415. Add Strings

时间:2018-10-27 11:28:40      阅读:153      评论:0      收藏:0      [点我收藏+]

stringbuilder加入到首位的话用insert

 

 1 class Solution {
 2     public String addStrings(String num1, String num2) {
 3         if(num1.length() == 0) return num2;
 4         if(num2.length() == 0) return num1;
 5         int i = num1.length()-1;
 6         int j = num2.length()-1;
 7         int carry = 0;
 8         StringBuilder sb = new StringBuilder();
 9         while(i >= 0 || j >= 0){
10             if(i < 0){
11                 int num = (num2.charAt(j) - ‘0‘ + carry) % 10;
12                 carry = (num2.charAt(j) - ‘0‘ + carry) / 10;
13                 sb.insert(0, num);
14                 j--;
15             }else if(j < 0){
16                 int num = (num1.charAt(i) - ‘0‘ + carry) % 10;
17                 carry = (num1.charAt(i) - ‘0‘ + carry) / 10;
18                 sb.insert(0, num);
19                 i--;
20             }else{
21                 int num = (num1.charAt(i)- ‘0‘ + num2.charAt(j) - ‘0‘ + carry) % 10;
22                 carry = (num1.charAt(i)- ‘0‘ + num2.charAt(j) - ‘0‘ + carry) / 10;
23                 sb.insert(0, num);
24                 i--;
25                 j--;
26             }
27         }
28         if(carry == 1){
29             sb.insert(0, 1);
30         }
31         return sb.toString();   
32         
33     }
34 }

 

415. Add Strings

原文:https://www.cnblogs.com/goPanama/p/9860459.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!