鍍金池/ 教程/ Java/ String to Integer (atoi)(轉換到整型)
ZigZag Conversion(Z型轉換)
String to Integer (atoi)(轉換到整型)
Generate Parentheses(生成括號)
Longest Common Prefix(最長公共前綴)
Remove Duplicates from Sorted Array(從已排序數組中移除重復元素)
Swap Nodes in Pairs(交換序列中的結點)
Valid Parentheses(有效的括號)
4 Sum(4 個數的和)
3 Sum(3 個數的和)
3 Sum Closest(最接近的 3 個數的和)
Reverse Nodes in k-Group(在K組鏈表中反轉結點)
Regular Expression Matching (正則表達式匹配)
Two Sum
Container With Most Water(最大水容器)
Merge Two Sorted Lists(合并兩個已排序的數組)
Remove Nth Node From End of List(從列表尾部刪除第 N 個結點)
String to Integer (atoi)(轉換到整型)
Palindrome Number(回文數)
Longest Substring Without Repeating Characters
Roman to Integer(羅馬數到整型數)
Integer to Roman(整型數到羅馬數)
Reverse Integer(翻轉整數)
Merge k Sorted Lists(合并 K 個已排序鏈表)
Implement strStr()(實現(xiàn) strStr() 函數)
Longest Palindromic Substring(最大回文子字符串)
Add Two Numbers
Letter Combinations of a Phone Number(電話號碼的字母組合)

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

翻譯

實現(xiàn)“atoi”將字符串轉換成整型數。

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

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

atoi 的要求:

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

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

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

如果可以不執(zhí)行任何有效的轉換,則返回零值。如果正確的值在值域范圍之外,則返回 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.

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

(好吧,在寫博客,也就上面的翻譯過程中,我發(fā)現(xiàn)題目懂了……)

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.