Big Integer Addition

题目描述:

Given two non-negative integers num1 and num2 represented as string, return the sum ofnum1 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"

分析:

老生常谈的加法题 //虽然总是记不住做法==
不能调用API中已有的Integer包里的方法,所以要利用的是ALU加法器的原理:

代码:

    public String addStrings(String num1, String num2) {
        // 利用的是ALU加法器的原理
        
        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]; //建立一个char数组来保存结果,多一位为进位
        for(int k=0;k<len+1;k++){
            result[k] = '0';
        }
        
        int p=0, X=0, Y=0;
        
        for(int i=0; i<len+1;i++){
            if(i<len1){
                X = num1.charAt(len1-i-1)-'0';
            }else{
                X = 0;
            }
            if(i<len2){
                Y = num2.charAt(len2-1-i)-'0';
            }else{
                Y = 0;
            }
            
            int temp = X + Y + p;  // 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值