LeetCode Online Judge 题目C# 练习 - Multiply Strings
2012-10-01 22:36
489 查看
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.
代码分析:
也是没有技巧的题目,细心注意输出的结果就行。
Note: The numbers can be arbitrarily large and are non-negative.
public static string MultiplyStrings(string num1, string num2) { if (num1.Length == 0 || num2.Length == 0) return "0"; int carry = 0; List<int> l1 = new List<int>(); List<int> l2 = new List<int>(); for (int i = num2.Length - 1; i >= 0; i--) { List<int> curr; if (l1.Count == 0) curr = l1; else { curr = l2; //Adding 0 to the end for (int k = i; k < num2.Length - 1; k++) { curr.Add(0); } } for (int j = num1.Length - 1; j >= 0; j--) { int b = num2[i] - '0'; int a = num1[j] - '0'; curr.Add(((a * b) % 10 + carry) % 10); carry = (a * b + carry) / 10; } if (carry > 0) curr.Add(carry); carry = 0; //Adding l1 and l2 into l1; if (l2.Count > 0) { int k = 0; while (k < l1.Count || k < l2.Count) { int a = k < l1.Count ? l1[k] : 0; int b = k < l2.Count ? l2[k] : 0; if (k < l1.Count) l1[k] = ((a + b + carry) % 10); else l1.Add((a + b + carry) % 10); carry = (a + b + carry) / 10; k++; } if (carry > 0) l1.Add(carry); carry = 0; } l2.Clear(); } string ret = ""; for (int i = l1.Count - 1; i >= 0; i--) { if (l1[i] != 0 || ret != "") ret = ret + l1[i].ToString(); } return ret == "" ? "0" : ret; ; }
代码分析:
也是没有技巧的题目,细心注意输出的结果就行。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Generate Parentheses
- LeetCode Online Judge 题目C# 练习 - Largest Rectangle in Histogram
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - N-QueensII
- LeetCode Online Judge 题目C# 练习 - Partition List
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List
- LeetCode Online Judge 题目C# 练习 - Scramble String
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Simplify Path
- LeetCode Online Judge 题目C# 练习 - Insert Interval
- LeetCode Online Judge 题目C# 练习 - Minimum Path Sum
- LeetCode Online Judge 题目C# 练习 - Next Permutation
- LeetCode Online Judge 题目C# 练习 - Permutation Sequence
- LeetCode Online Judge 题目C# 练习 - Integer to Roman
- LeetCode Online Judge 题目C# 练习 - Remove Nth Node From End of List
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees
- LeetCode Online Judge 题目C# 练习 - Jump Game
- LeetCode Online Judge 题目C# 练习 - Palindrome Number
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II