leetcodeOJ 43. Multiply Strings

来源:互联网 发布:厦门市公安局网络公章 编辑:程序博客网 时间:2024/05/21 11:21

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

Note:

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

代码如下:
class Solution {public:    string multiply(string num1, string num2) {        string ans(num1.size()+num2.size(), '0');                for(int i = num1.size()-1; i >= 0; i--){            int c = 0; //进位            for(int j = num2.size()-1; j >= 0; j--){                int temp = (ans[i+j+1] - '0') + (num1[i] - '0') * (num2[j] - '0') + c;                ans[i+j+1] = temp % 10 + '0';                c = temp / 10;            }            ans[i] += c;        }        int where = ans.find_first_not_of('0');        if(string::npos == where){            return "0";        }        return ans.substr(where);    }};

0 0