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 public static string MultiplyStrings(string num1, string num2) 2 { 3 if (num1.Length == 0 || num2.Length == 0) 4 return "0"; 5 6 int carry = 0; 7 List<int> l1 = new List<int>(); 8 List<int> l2 = new List<int>(); 9 for (int i = num2.Length - 1; i >= 0; i--) 10 { 11 List<int> curr; 12 if (l1.Count == 0) 13 curr = l1; 14 else 15 { 16 curr = l2; 17 //Adding 0 to the end 18 for (int k = i; k < num2.Length - 1; k++) 19 { 20 curr.Add(0); 21 } 22 } 23 24 for (int j = num1.Length - 1; j >= 0; j--) 25 { 26 int b = num2[i] - '0'; 27 int a = num1[j] - '0'; 28 29 curr.Add(((a * b) % 10 + carry) % 10); 30 carry = (a * b + carry) / 10; 31 } 32 33 if (carry > 0) 34 curr.Add(carry); 35 36 carry = 0; 37 38 //Adding l1 and l2 into l1; 39 if (l2.Count > 0) 40 { 41 int k = 0; 42 while (k < l1.Count || k < l2.Count) 43 { 44 int a = k < l1.Count ? l1[k] : 0; 45 int b = k < l2.Count ? l2[k] : 0; 46 47 if (k < l1.Count) 48 l1[k] = ((a + b + carry) % 10); 49 else 50 l1.Add((a + b + carry) % 10); 51 carry = (a + b + carry) / 10; 52 53 k++; 54 } 55 56 if (carry > 0) 57 l1.Add(carry); 58 59 carry = 0; 60 } 61 l2.Clear(); 62 } 63 64 string ret = ""; 65 for (int i = l1.Count - 1; i >= 0; i--) 66 { 67 if (l1[i] != 0 || ret != "") 68 ret = ret + l1[i].ToString(); 69 } 70 71 return ret == "" ? "0" : ret; ; 72 }
代码分析:
也是没有技巧的题目,细心注意输出的结果就行。