Reputation: 101
Let's get straight to the point. I made the following code to multiply two numbers and it's "eating" my zeroes! It seems to work fine for cases which don't involve having a product (p) that is equal to zero. In the sample case it simply prints "5" instead of the desired "500". I'd be really thankful if anyone cared to explain what's going on. :)
using System;
class Program
{
static void Main()
{
Console.WriteLine(smallNumBigNumProduct("5", "100"));
}
static string smallNumBigNumProduct(string s, string b)
{
int l = s.Length;
int f = int.Parse(s); // factor
int c = 0; // carry
string r = ""; // result
int p; // product
while(l-- > 0)
{
p = (Convert.ToInt32(b[l]) - 48) * f;
p += c;
if (p > 9)
{
r = Convert.ToString(p % 10) + r;
c = p / 10;
}
else
r = Convert.ToString(p) + r;
}
if (c > 0)
{
r = Convert.ToString(c) + r;
}
return r;
}
}
Upvotes: 3
Views: 509
Reputation: 300529
How about:
public static string smallNumBigNumProduct(string a, string b)
{
// NOTE no error checking for bad input or possible overflow...
int num1 = Convert.ToInt32(a);
int num2 = Convert.ToInt32(b);
return ((num1*num2).ToString());
}
Or even better if you are using .NET 4.0 (updated thanks to Gabe's prompting):
public static string smallNumBigNumProduct(string a, string b)
{
// NOTE no error checking for bad input or possible overflow...
BigInteger num1 = BigInteger.Zero;
BigInteger num2 = BigInteger.Zero;
bool convert1 = BigInteger.TryParse(a, out num1);
bool convert2 = BigInteger.TryParse(b, out num2);
return (convert1 && convert2) ? (num1*num2).ToString() : "Unable to convert";
}
Upvotes: 4
Reputation: 498942
Here is your problem:
int l = s.Length;
...
while(l-- > 0)
You are setting your l
variable to the length of the short string, then in your while
loop you pre-decrement it.
In short, your loop isn't executed the number of times you think it is. Shouldn't the l
variable be set to the length of the b
string?
Regardless, this looks like a long and error prone way to do this. Why not simply convert the input strings to integers and return the product directly?
Upvotes: 5