[LeetCode]题解(python):008-String to Integer (atoi)

 

题目来源:

https://leetcode.com/problems/string-to-integer-atoi/


题意分析:

      这道题也是简单题,题目意思是要将字符串转化成int。比如‘123’转成123.


题目思路:

     由于有一些其他的输入直接用int()函数肯定是不可以的。比如说‘123b’用int()函数肯定是报错的。那么我们可以用一个ans = 0来初始化得到的int,从第一个字符s开始判断,得到新的ans是ans = ans*10 + int(s)。题目要注意的是一些特殊情况:

1.刚开始的空格,字符开始的空格字符忽略不算;

2.‘-’和‘+’字符,第一次出现的这两个字符可以代表得到的int的正负;

3.上述情况以外的所有非‘0’-‘9’的字符,出现这些字符的时候等于出现结束符;

4.得到的ans超过32位int最大长度。

只要在代码中加上几个bool判断符,字符的一些比较和ans的大小比较一下,答案就出来了。


代码(python):

 1 class Solution(object):
 2     def myAtoi(self, str):
 3         """
 4         :type str: str
 5         :rtype: int
 6         """
 7         size = len(str)
 8         if size == 0:
 9             return 0
10         ans = 0
11         b = True
12         b1 = True
13         positive = True
14         i = 0
15         while i < size:
16             if str[i] != ' ':
17                 b1 = False
18             if str[i] == ' ' and b1:
19                 i += 1
20                 continue
21             if b:
22                 if str[i] =='-':
23                     positive = False
24                     i += 1
25                     b = False
26                     continue
27                 if str[i] == '+':
28                     i += 1
29                     b = False
30                     continue
31             if str[i]>= '0' and str[i] <= '9':
32                 ans = ans*10 + int(str[i])
33                 if ans > 2147483647 and positive:
34                     return 2147483647
35                 if ans > 2147483648 and not positive:
36                     return - 2147483648
37             else:
38                 break
39             i += 1
40         if positive:
41             return ans
42         return -1 * ans
View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/4801655.html

原文地址:https://www.cnblogs.com/chruny/p/4801655.html