开发者

Simple multiplication

开发者 https://www.devze.com 2023-02-25 03:52 出处:网络
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 eq

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


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?


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

精彩评论

暂无评论...
验证码 换一张
取 消