1. 程式人生 > >LeetCode 8 String to Integer (atoi)(轉換到整型)

LeetCode 8 String to Integer (atoi)(轉換到整型)

翻譯

實現“atoi”將字串轉換成整型數。

提示:仔細考慮所有可能的輸入。如你想要挑戰,請不要參閱下面並問問自己都有哪些可能的輸入請看。

說明:模糊的指定(沒有給定的輸入規格)就是為了這個問題。你負責收集所有可能的輸入。

atoi的要求:

函式首先放棄儘可能多的空字元直到找到一個非空白字元。然後從這個字元開始,帶上可選的初始加/減字元,其後還可能跟著越多越好的數字,並將它們解釋成一個數值。

這個字串可能在這些數字之後包含一些附加的字元,它們可以可以被忽略,並對函式的行為沒有影響。

如果字串str中第一個非空格的序列不是一個有效的整型數,或者因為str為空或僅有空格字元而不存在這樣一個序列,那麼不執行任何轉換。

如果可以不執行任何有效的轉換,則返回零值。如果正確的值在值域範圍之外,則返回INT_MAX(2147483647
)或INT_MIN(-2147483647)。

原文

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given
input specs). You are responsible to gather all the input requirements up front. Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by
as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

英語渣渣實在沒看懂題目,不知道有哪些條件,於是就慢慢寫程式碼,根據報錯繼續改……結果程式碼改到了80行……還是不能完成所有條件,還是從網上蕩了一個下來,來日再戰!

(好吧,在寫部落格,也就上面的翻譯過程中,我發現題目懂了……)

public class Solution
{
    public int MyAtoi(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return 0;
        }
        var result = 0;
        var i = 0;
        // clean all the whitespaces in the beginning
        while (i < str.Length && str[i] == ' ')
        {
            i++;
        }
        // check positive or negative sign
        var sign = 1;
        switch (str[i])
        {
            case '-':
                sign = -1;
                i++;
                break;
            case '+':
                sign = 1;
                i++;
                break;
        }
        // check the rest of numbers
        while (i < str.Length && str[i] >= '0' && str[i] <= '9')
        {
            // check overflow
            try
            {
                checked
                {
                    result = result * 10 + (str[i++] - '0');
                }
            }
            catch (OverflowException)
            {
                return sign == 1 ? int.MaxValue : int.MinValue;
            }
        }
        return sign * result;
    }
}
1045 / 1045 test cases passed.
Status: Accepted
Runtime: 168 ms
Your runtime beats 16.85% of csharp submissions.