實現(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.