码迷,mamicode.com
首页 > 其他好文 > 详细

43. Multiply Strings

时间:2018-03-10 22:05:06      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:code   ack   a*   bre   source   push   div   reverse   没有   

43. Multiply Strings

题目

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

    The length of both num1 and num2 is < 110.
    Both num1 and num2 contains only digits 0-9.
    Both num1 and num2 does not contain any leading zero.
    You must not use any built-in BigInteger library or convert the inputs to integer directly.

解析

  • 大数相乘原则
  • 认清楚乘法从后面开始乘,vec[size-1]是最小位
// add 43. Multiply Strings
class Solution_43 {
public:
    string multiply(string num1, string num2) {
        int len1 = num1.size();
        int len2 = num2.size();

        vector<int> vec(len1+len2,0); // 初始化内存空间
        //vec.reserve(len1 + len2);
        
        for (int i = 0; i < len1; i++)
        {
            int k = i;
            for (int j = 0; j < len2;j++)
            {
                //vec.push_back(a*b);
                vec[k] += (num1[len1-1-i] - '0')*(num2[len2-1-j]-'0');  ////Calculate from rightmost to left
                k++; 
            }
        }

        string ret="";
        for (int i = 0; i < vec.size();i++)
        {
            if (vec[i]>=10)
            {
                vec[i+1] += vec[i] / 10;
                vec[i] = vec[i] % 10;
            }
            //char temp[5];
            //_itoa(vec[i], temp, 10);
            //ret += temp;

            char temp = vec[i] + '0'; 
            ret += temp; //反着取得
        }

        //reserve(ret.begin(),ret.end());
        //reverse(vec.begin(), vec.end()); //string没有反转函数,vector有
        
        //判断第一个非0位 //size_t startpos = sum.find_first_not_of("0");
        int flag = 0;
        for (int i = ret.size()-1; i >=0;i--)
        {
            if (ret[i]!='0')
            {
                flag = i;
                break;
            }
        }

        int begin = 0, end = flag;
        while (begin < end)
        {
            swap(ret[begin], ret[end]);
            begin++;
            end--;
        }

        return ret.substr(0,flag+1);
    }
};

题目来源

43. Multiply Strings

标签:code   ack   a*   bre   source   push   div   reverse   没有   

原文地址:https://www.cnblogs.com/ranjiewen/p/8541787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!