Big Integer Addition

版权声明:本文为博主原创文章,未经博主允许不得转载。博主水平有限,欢迎指教 https://blog.csdn.net/Follower_JC/article/details/72888128

题目描述:

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;
    }



猜你喜欢

转载自blog.csdn.net/Follower_JC/article/details/72888128