您的位置:首页 > 编程语言 > C#

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.

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; ;
}


代码分析:

  也是没有技巧的题目,细心注意输出的结果就行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: