標籤:
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.
給出兩個字串,返回對應數字想乘後的字串,由於這個字串可能很大,所以不能採用一般的乘法,這裡用的方法是類比手工的乘法運算,演算法
本身很簡單,就是當時寫的時候有些很小的細節搞錯了,找了很久的錯。啊啊啊啊啊,要細心啊。大媽如下,沒什麼好說的:
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 if(num1 == "0" || num2 == "0") return "0"; 5 int steps = 0; 6 int pos = 0; 7 int flag = 0; 8 int val = 0; 9 string result = "";10 reverse(num1.begin(), num1.end());11 reverse(num2.begin(), num2.end());12 int len1 = num1.length();13 int len2 = num2.length();14 for(int i = 0; i < len1; ++i){15 pos = steps;16 for(int j = 0; j < len2; ++j){17 val = (num1[i] - ‘0‘)*(num2[j] - ‘0‘) + flag;18 if(result.size() <= pos){19 result.append(1, val%10 + ‘0‘);20 }else{21 val += (result[pos] - ‘0‘);22 result[pos] = val%10 + ‘0‘;23 }24 flag = val/10;25 pos++; 26 }27 if(flag > 0)28 result.append(1, flag + ‘0‘);29 flag = 0;30 steps++;31 }32 reverse(result.begin(), result.end());33 return result;34 }35 };
LeetCode OJ:Multiply Strings (字串乘法)