2011-04-17 73 views
3

讓我們直接點。我做了下面的代碼來乘以兩個數字,它「吃」我的零點!對於不涉及產品(p)等於零的情況,它似乎工作正常。在示例中,它僅打印「5」而不是所需的「500」。如果有人在意解釋發生了什麼,我會非常感激。 :)簡單的乘法運算

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

我不明白你的意思。 :p – Codetester 2011-04-17 06:04:16

+0

哎呀...我剛看到我的錯誤。 – Codetester 2011-04-17 06:07:54

+3

一個字母的變量名稱會傷害你*和*我。 – arcain 2011-04-17 06:16:06

回答

5

這裏是你的問題:

int l = s.Length; 

... 

while(l-- > 0) 

您正在設置您的l可變長度的字符串,然後在你的while循環中預先遞減它。

簡而言之,您的循環不會執行您認爲它的次數。不應將l變量設置爲b字符串的長度嗎?

無論如何,這看起來像一個長期和容易出錯的方式來做到這一點。爲什麼不簡單地將輸入字符串轉換爲整數並直接返回產品?

+0

我已經修復了這個錯誤!我打算用b,而不是l。輕微忽略!謝謝!我這樣做的原因是能夠將一個小數字與一個有幾十個數字的數字相乘。 – Codetester 2011-04-17 06:16:31

+2

因此,在.NET 4.0中引入的[BigInteger](http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx)無法爲您工作? – Oded 2011-04-17 06:17:48

+0

我使用這個SPOJ問題,不知道我是否可以在那邊使用BigInteger。 – Codetester 2011-04-17 06:27:39

4

如何:

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

或者即使你使用的是.NET 4.0更好(更新感謝Gabe的提示):

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

你真的認爲只有'Convert.ToInt32'才能實現名稱中帶有「BigNum」的函數嗎?我的意思是,你至少要使用'long'或'decimal'。沒有提到哪一個,即使'BigInteger'解決方案因爲在進行乘法之前轉換爲'Int64'而被破壞。 – Gabe 2011-04-17 06:40:01

+0

@加貝:好點。 – 2011-04-17 06:54:40