当前位置:网站首页>Niuke.com: large number addition

Niuke.com: large number addition

2022-06-21 17:20:00 lsgoose

It is essentially a simulation of arithmetic :

When we calculate, we must first align the lowest order , Then add them bit by bit , In addition, only one digit is added at a time , Record this carry , Add it to the next time .

The code is as follows :

class Solution {
public:
    /**
     *  The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly 
     *  Calculate the sum of two numbers 
     * @param s string character string   Represents the first integer 
     * @param t string character string   Represents the second integer 
     * @return string character string 
     */
    string solve(string s, string t) {
        if(s=="") return t;
        if(t=="") return s;
        int carry=0;
        // Ensure the length of the preceding string is long 
        if(s.length()<t.length()){
            swap(s, t);
        }
        for(int i=s.length()-1;i>=0;i--){
            int sum=s[i]-'0'+carry;
            // Find the corresponding bit in a shorter string t Position in 
            int j=(t.length()-s.length())+i;
            if(j>=0){
                sum+=t[j]-'0';
            }
            carry=sum/10;
            sum=sum%10;
            s[i]='0'+sum;
        }
        if(carry){
            s='1'+s;
        }
        return s;
    }
};

原网站

版权声明
本文为[lsgoose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211405237914.html