Created
February 18, 2013 15:13
-
-
Save pdu/4978107 to your computer and use it in GitHub Desktop.
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://leetcode.com/onlinejudge#question_43
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define MAXN 10000 | |
| int f[MAXN]; | |
| class Solution { | |
| public: | |
| string multiply(string num1, string num2) { | |
| int n = num1.length(); | |
| int m = num2.length(); | |
| memset(f, 0, sizeof(f)); | |
| for (int i = m - 1; i >= 0; --i) { | |
| int st = m - 1 - i; | |
| for (int j = n - 1; j >= 0; --j) { | |
| f[st++] += (num2[i] - '0') * (num1[j] - '0'); | |
| } | |
| } | |
| for (int i = 0; i < n + m; ++i) { | |
| f[i + 1] += f[i] / 10; | |
| f[i] %= 10; | |
| } | |
| int len; | |
| for (len = n + m - 1; len >= 0; --len) | |
| if (f[len] != 0) | |
| break; | |
| len = max(len, 0); | |
| string ans; | |
| for (int i = len; i >= 0; --i) { | |
| char c = '0' + f[i]; | |
| ans += c; | |
| } | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment