lintcode(655)Big Integer Addition

描述:

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

 注意事项
  • The length of both num1 and num2 is < 5100.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

样例:

Given num1 = "123", num2 = "45"
return "168"

思路:

建立char数组存储结果,比字符串长度加1 以保存进位 最后要去除起始的0

public class Solution {
    /**
     * @param num1 a non-negative integers
     * @param num2 a non-negative integers
     * @return return sum of num1 and num2
     */
    public String addStrings(String num1, String num2) {
        // Write your code here
        if(num1.equals("0")){
            return num2;
        }
        if(num2.equals("0")){
            return num1;
        }
        int len1 = num1.length();
        int len2 = num2.length();
        
        int len = Math.max(len1 , len2);
        char[] result = new char[len + 1];
        for(int k = 0;k<len + 1;k++){
            result[k] = '0';
        }
        
        int p = 0;
        int n1 = 0;
        int n2 = 0;
        for(int i = 0;i<len + 1;i++){
            if(i < len1){
                n1 = num1.charAt(len1 - 1 - i) - '0';
            }else{
                n1 = 0;
            }
            if(i < len2){
                n2 = num2.charAt(len2 - 1 - i) - '0';
            }else{
                n2 = 0;
            }
            int temp = n1 + n2 + p;
            result[len - i] = (char)(temp%10 + '0');
            p = temp/10;
        }
        int count = 0;
        for(;count<len + 1;count++){
            if(result[count] != '0'){
                break;
            }
        }
        String res = "";
        for(int i = count;i<len + 1;i++){
            res += result[i];
        }
        return res;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值