2013-11-28 27 views
0

我們有這個編碼練習手動執行Int.Parse淨如何手動編程Int.Parse()

()方法

我沒有得到他們的「正確」的解決方案是如何工作的。但我記得它包含了十分之一,百分之一的因子...

我發現了一個用Java函數完成的解決方案。有人可以向我解釋如何將數字乘以幾十個字符串解析爲int嗎?

public static int myStringToInteger(String str) { 
    int answer = 0, factor = 1; 
    for (int i = str.length()-1; i >= 0; i--) { 
     answer += (str.charAt(i) - '0') * factor; 
     factor *= 10; 
    } 
    return answer; 
} 
+3

取紙和一支筆,一步步嘗試看看會發生什麼。 – RamonBoza

+0

你有沒有試過寫出跑步?說,在輸入「235」? –

+4

提示:1234 = 4 +(3 * 10)+(2 * 10 * 10)+(1 * 10 * 10 * 10) – Rik

回答

0

我們假設它獲得以下字符串:"";

答案實際上是迭代值的總和,從0開始。 因子是您乘以第n位的乘數。

它這樣做,主要有:

answer = 0 

factor = 1 
answer = answer + (4 * 1) = 0 + 4 = 4; 

factor = 10; 
answer = answer + (3 * 10) = 4 + 30 = 34; 

factor = 100; 
answer = answer + (2 * 100) = 34 + 200 = 234; 

factor = 1000; 
answer = answer + (1 * 1000) = 234 + 1000 = 1234; 

factor = 1000; 
answer = answer + (0 * 10000) = 1234 + 0 = 1234; 

當然,你需要在字符串包含的東西比普通的數字更採取了這樣的情況。

1

這是使用LINQ的方式之一,

string st = "1234785"; 
    int i = 0; 
    int counter = 0; 
    st.All(x => { 
    if (char.IsDigit(x)) 
    { 
     i += (int)(char.GetNumericValue(x) * Math.Pow(10, (st.Length - counter - 1))); 
    } 
    counter++; 
    return true; 
}); 

在此之後,我= 1234785.

,如果你把一些字符串,如「你好」,它會返回0給你,如果你傳遞字符串「Hello 123」 那麼將返回123

1

其實這不是地方讓你在家工作:-)做

不過,我記得,分析我的F ist程序來理解「人們如何做這些事情」。 在以後的時間裏,我總是習慣將外國代碼重構成我能理解的小塊。

所以,對於上面的代碼,這可能是:

public static int myStringToInteger(String str) { 
    int answer = 0; 
    int factor = 1; 

    // Iterate over all characters (from right to left) 
    for (int i = str.length() - 1; i >= 0; i--) { 

     // Determine the value of the current character 
     // (I guess this is the trick you were missing 
     // We extract a single character, subtract the 
     // ASCII value the character '0', getting the "distance" 
     // from zero. So we converted a single character into 
     // its integer value) 
     char currentCharacter = str.charAt(i); 
     int value = currentCharacter - '0'; 

     // Add the value of the character at the right place 
     answer += value * factor; 

     // Step one place further 
     factor *= 10; 
    } 

    return answer; 
} 
+0

雖然感謝。這不是一個家庭作業,我只是想了解這個。我發現我誤解了這個問題。 – NullReferenceException