[leetcode algorithms]題目8
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.
自己寫的代碼:
本來想寫for循環來檢驗字元串的,寫起來發現太麻煩了,於是湊不要捻地用了正則表達式[捂臉]。運行時間119 ms。
class Solution: def myAtoi(self, str): INT_MAX = 2147483647 INT_MIN = -2147483648 p = re.compile("^s*(+?|-?)d+") try: res = int(p.match(str).group().replace( , )) except: res = 0 return max(INT_MIN, min(INT_MAX, res))
推薦閱讀:
※[leetcode algorithms]題目18
※[leetcode algorithms]題目1
※真的智障,真寫不出來,88-Merge Sorted Array
※008 String to Integer (atoi)[M]
※LeetCode 簡略題解 - 301~400
TAG:LeetCode |