實現atoi函數(string轉integer)
String to Integer (atoi)
- Implement atoi to convert a string to an integer.
- Hint: Carefully consider all 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..
Example 1:
Input: ""
Output: 0
- Example 2:
Input: "+2"
Output: 2
- Example 3:
Input: "+-2"
Output: 0
- Example 4:
Input: "+"
Output: 0
- Example 5:
Input: "-223pasudasd"
Output: -223
思路
- 利用Python內置的int(str)函數可以將字符串快速轉換成int型
- 利用int(str)是否拋出異常來快速判斷str能否被轉換成int,進而迅速確定輸入字符串中第一個非數字字符的位置
- 需要注意處理
+
,-
符號的問題
代碼
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
retstr = ''
try:
for _, item in enumerate(s):
if item == '+' or item == '-':
retstr += item
else:
retstr += str(int(item))
finally:
if len(retstr) == 0:
return 0
else:
try:
# 如果 retstr 是 '-' 或者 '+',len(retstr) != 0 但是會拋出異常,此時返回0
# 由於python的int沒有取值上限,如果規定int爲32位,需要判斷int(retstr)是否大於2147483647或者小余-2147483648
return int(retstr)
except:
return 0
本題以及其它leetcode題目代碼github地址: github地址