題目描述
LeetCode 8 String to Integer (atoi)
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.
題目大意
實(shí)現(xiàn)atoi函數(shù)將字符串轉(zhuǎn)換為整數(shù)氢烘。
提示:仔細(xì)考慮所有輸入用例肋演。如果想給自己挑戰(zhàn)斥滤,請不要看下面的內(nèi)容并詢問自己所有可能的輸入用例。
注意:這道題有意描述地比較含糊(亦即误堡,沒有給出輸入用例)。你需要自己發(fā)掘所有的輸入要求毯辅。
atoi的要求:
函數(shù)首先盡可能多的丟棄空白字符埂伦,直到發(fā)現(xiàn)第一個(gè)非空字符位為止。 接著從這個(gè)字符開始思恐,讀入一個(gè)可選的正負(fù)號沾谜,然后盡可能多的讀入數(shù)字,最后將它們解析成數(shù)值胀莹。
字符串中在合法數(shù)字后可以包含額外的非法字符基跑,對于這些字符只需丟棄即可。
如果字符串的非空字符不是一個(gè)有效的整數(shù)描焰,或者媳否,當(dāng)字符串為空或者只包含空白字符時(shí),不需要執(zhí)行轉(zhuǎn)換荆秦。
如果不能夠執(zhí)行有效的轉(zhuǎn)換則返回0篱竭。如果得到的數(shù)值超出了整數(shù)范圍,返回INT_MAX (2147483647) 或者 INT_MIN (-2147483648)步绸。
要點(diǎn)分析
Input Edge Case
How to catch exceptions and corner case掺逼?往往一個(gè)函數(shù)或者程序的輸入是有很多Edge Case的,為了程序的robustness瓤介,我們需要處理這些異常的Case吕喘。
python源碼
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0:
return 0
str = str.strip()
start = 1 if str[0] in ('+','-') else 0
res = 0
for i in range(start, len(str)):
if not str[i].isdigit():
break
res = res*10 + ord(str[i]) - ord('0')
res *= (-1 if str[0] == '-' else 1)
return max(-2147483648, min(res,2147483647))
Tips
1 用max和min減少if else
max(min_value, min(res, max_value))
2 str.strip([chars])
[可指定移除字符串頭尾的任意字符](默認(rèn)為空格)
chars -- 移除字符串頭尾指定的字符
3 isdigit()
方法檢測字符串是否只由數(shù)字組成(單個(gè)字符和字符串都可以)
4 ord()
ord() 函數(shù)是 chr() 函數(shù)(對于8位的ASCII字符串)或 unichr() 函數(shù)(對于Unicode對象)的配對函數(shù)
它以一個(gè)字符(長度為1的字符串)作為參數(shù)赘那,
返回對應(yīng)的 ASCII 數(shù)值,或者 Unicode 數(shù)值氯质,
如果所給的 Unicode 字符超出了你的 Python 定義范圍募舟,則會(huì)引發(fā)一個(gè) TypeError 的異常。
ord(char) - ord('0')