1. 程式人生 > >LeetCode-43. 字串相乘

LeetCode-43. 字串相乘

題目地址:https://leetcode-cn.com/problems/multiply-strings/
思路:模擬乘法。
AC程式碼:

class Solution {
public:
    string multiply(string num1, string num2) {
        char ans[225];
        int ans2[225];
        memset(ans,0,sizeof(ans));
        memset(ans2,0,sizeof(ans2));
        int length1 = num1.size();
        int length2 = num2.size();
        for(int i=0;i<length1;i++)
            for(int j=0;j<length2;j++){
                int now = (num1[i]-'0')*(num2[j]-'0');
                ans2[i+j+1] += now;
            }
        int  flag = 0;
        for(int i = length1+length2-1;i>=0;i--){
            int now = ans2[i]+flag;
            flag = now/10;
            now = now%10;
            ans[i] = now+'0';
        }
        char* res = ans;
        for(int i=0;i<length1+length2;i++)
            if(ans[i]!='0')
                return res;
            else
                res++;
        return "0";
    }
};