一、题目
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.
把字符串转换成数字
atoi函数要求:
(1)开头去除空格,判断字符串是“+”或者“-”,然后后面跟尽量多的数字
(2)如果不是字符串或者不是有效的整数,则不执行转换
(3)不执行转换返回0,正确值超出了可表示值的范围,则返回2147483647或者-2147483648
二、思路
1、首先判断给定的是否是字符串;
2、去除首位的空格,然后判断正负
3、遍历字符串,遇到0-9之外的就break
4、越界处理
三、代码
#coding:utf-8 def myAtoi0(str): """ :type str: str :rtype: int """ if str == '' or not str: return 0 str = str.strip() integer,signal = 0,1 if str[0] == '+': str = str[1:] elif str[0] == '-': signal = -1 str = str[1:] for item in str: if item >= '0' and item <= '9': integer = integer*10 + ord(item) - ord('0') else: break integer = signal*integer integer = integer if integer <= 2147483647 else 2147483647 integer = integer if integer >= -2147483647 else -2147483647 print(integer) import re def myAtoi1(str): """ :type str: str :rtype: int """ str = str.strip() try: """ 正则表达式 http://www.runoob.com/python/python-reg-expressions.html http://www.jb51.net/article/73342.htm re.M|re.I re.I 不区分大小写 re.M 将所有行的尾字母输出 re.search 扫描整个字符串并返回第一个成功的匹配。 re.search(pattern, string, flags=0) re.match 只匹配开头,开头没有就返回False """ res = re.search('(^[+-]?d+)',str).group() res = int(res) res = res if res <= 2147483647 else 2147483647 res = res if res >= -2147483648 else -2147483648 except: res = 0 print(res) return res if __name__ == '__main__': str = ' -123a' myAtoi0(str) myAtoi1(str)
参考博客:https://www.cnblogs.com/zywscq/p/5325604.html
条件表达式:https://www.cnblogs.com/Xeonilian/p/python-conditional-expression.html