Loading

LeetCode 043 Multiply Strings

题目要求:Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

 

分析:

参考网址:http://blog.csdn.net/pickless/article/details/9235907

利用竖式的思想,进行乘法运算。

 

        3    4

*      1    3

——————

       9      12

3     4

——————

3     13     12

 

再处理进位:

3 13 12 - > 3 14 2 -> 4 4 2

 

代码如下:

class Solution {
public:
    string multiply(string num1, string num2) {

        int flag = 1;
        
        //先处理符号
        if (num1[0] == '-' || num2[0] == '-') {
            if (num1[0] == '-') {
                flag *= -1;
                num1 = num1.substr(1, num1.size() - 1);
            }
            if (num2[0] == '-') {
                flag *= -1;
                num2 = num2.substr(1, num2.size() - 1);
            }
        }
        
        int length = num1.size() + num2.size() + 1;
        int s[length];
        
        memset(s, 0, sizeof(int) * length);
        
        int i = 0, temp = 0;
        
        for (i = 0; i < num1.size(); i++) {
            for (int j = 0; j < num2.size(); j++) {
                s[(num1.size() - i - 1) + (num2.size() - j - 1)] += (num1[i] - '0') * (num2[j] - '0');
            }
        }
        
        //进位
        for (i = 0; i < length; i++) {
            s[i + 1] += s[i] / 10;
            s[i] = s[i] % 10;
        }
        
        for (i = 0; i < length / 2; i++) {
            temp = s[i];
            s[i] = s[length - i - 1];
            s[length - i - 1] = temp;
        }
        
        string ans = flag < 0 ? "-" : "";
        for (i = 0, temp = -1; i < length; i++) {
            if (s[i] != 0) {
                temp = 1;
            }
            if (temp > 0) {
                ans += s[i] + '0';
            }
        }
        return ans == "" ? "0" : ans;
    }
};

 

posted @ 2015-02-07 20:29  Yano_nankai  阅读(132)  评论(0编辑  收藏  举报