码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-415. Add Strings

时间:2017-03-31 19:53:07      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:res   uil   代码   class   contains   pre   leading   car   represent   

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.

java代码:

public class Solution {
    public String addStrings(String num1, String num2) {
        int len1=num1.length()-1;
        int len2=num2.length()-1;
        StringBuilder sb=new StringBuilder();
        int sum=0,carry=0;
        while(len1>=0||len2>=0){
            int a=len1>=0?num1.charAt(len1)-‘0‘:0;
            int b=len2>=0?num2.charAt(len2)-‘0‘:0;
            sum=a+b+carry;
            if(sum>9){
                sb.insert(0,sum%10);
                carry=1;
                sum=0;
            }else{
                sb.insert(0,sum);
                sum=0;
                carry=0;
            }
            len1--;
            len2--;
        }
        if(carry==1){
            sb.insert(0,1);
        }
        return sb.toString();
    }
}

  

 

leetcode-415. Add Strings

标签:res   uil   代码   class   contains   pre   leading   car   represent   

原文地址:http://www.cnblogs.com/lcbg/p/6653054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!