[leetcode]Multiply Strings

高精度大数相乘。首先是用数组存大数,然后关键的是ans[i+j] += num1[i]*num2[j]。数组中的数这时可能会大于10,就扫一遍做进位处理。

编写中犯过的两个错:1.ans[i+j] += num1[i]*num2[j]没有写+;2.略过末尾的0时,忘记判断index>=0;3.如果结果是0,就是所有的都是0时,要单独返回“0”

参考:http://blog.csdn.net/u011328276/article/details/9464817

public class Solution {

    public String multiply(String num1, String num2) {

        int ans[] = new int[num1.length()+num2.length()];

        int len1 = num1.length();

        int len2 = num2.length();

        for (int i = 0; i < len1; i++)

        {

            for (int j = 0; j < len2; j++)

            {

                ans[i+j] += (num1.charAt(len1-i-1) - '0') * 

                            (num2.charAt(len2-j-1) - '0');

            }

        }

        for (int i = 0; i < len1+len2; i++)

        {

            if (ans[i] >= 10)

            {

                ans[i+1] += ans[i] / 10;

                ans[i] = ans[i] % 10;

            }

        }

        StringBuffer sb = new StringBuffer();

        int i = len1+len2-1;

        while (i >= 0 && ans[i] == 0)

        {

            i--;

        }

        for (; i >= 0; i--)

        {

            sb.append(ans[i]);

        }

        String result = sb.toString();

        if (result.length() == 0) return "0";

        else return result;

    }

}

second time:

class Solution {

public:

    string multiply(string num1, string num2) {

        reverse(num1.begin(), num1.end());

        reverse(num2.begin(), num2.end());

        vector<char> ans(num1.size() + num2.size());

        for (int i = 0; i < num1.size(); i++)

        {

            for (int j = 0; j < num2.size(); j++)

            {

                ans[i+j] += (num1[i] - '0') * (num2[j] - '0');

                ans[i+j+1] += ans[i+j] / 10;

                ans[i+j] = ans[i+j] % 10;

            }

        }

        string s;

        bool nonzero = false;

        for (int i = ans.size()-1; i >= 0; i--)

        {

            if (!nonzero && ans[i] == 0)

                continue;

            nonzero = true;

            s.push_back((char) (ans[i]+'0'));

        }

        if (s == "") return "0";

        return s;

    }

};

  

你可能感兴趣的:(LeetCode)