Easy understand C++


  • 0
    B
    class Solution {
        //大数相乘 and 大数相加
    public:
        string multiply(string num1, string num2) {
            int len1 = num1.size();
            int len2 = num2.size();
            string res = "";
            for(int i = len1 - 1; i>=0;i--)
            {
                string s = "";
                int sum = 0;
                for(int j = len2 - 1; j>=0;j--)
                {
                    int temp = 0;
                    sum += (num2[j] - '0') * (num1[i] - '0');
                    temp = sum%10;
                    sum /= 10;
                    s += (temp + '0'); 
                }
                if(sum != 0) s += (sum + '0');
                for(int k = 0;k<len1-1-i;k++)
                {
                    s = '0' + s;
                }
                res = add(res,s);
            }
            reverse(res.begin(),res.end());
            int i = 0;
            for(i;i < res.size() ; i++)
            {
               if(res[i] != '0') break;
            }
            return i==res.size()?"0":res;
        }
        string add(string res,string s)//每次都逆序进来
        {
            int len1 = res.size() - 1;
            int len2 = s.size() - 1;
            reverse(res.begin(),res.end());
            reverse(s.begin(),s.end());
            int sum = 0;
            string k = "";
            while(len1 >= 0 || len2 >= 0 || sum>0)
            {
                if(len1 >= 0)
                {
                    sum += (res[len1--] - '0');
                }
                if(len2 >= 0)
                {
                    sum += (s[len2--] - '0');
                }
                k += (sum%10 + '0');
                sum /= 10;
            }
            return k;
        }
    };
    ···

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.