File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 7.1 案例一
2
+
3
+ ## 面试题49 把字符串转化成整数
4
+ > 要求:把字符串转化成整数
5
+ >
6
+ > 测试用例:正负数和0,空字符,包含其他字符
7
+ >
8
+ > 备注:使用raise抛出异常作为非法提示
9
+
10
+ ``` python
11
+ def str_to_int (string ):
12
+ if not string: # 空字符返回异常
13
+ raise Exception (' string cannot be None' , string)
14
+ flag = 0 # 用来表示第一个字符是否为+、-
15
+ ret = 0 # 结果
16
+ for k, s in enumerate (string):
17
+ if s.isdigit(): # 数字直接运算
18
+ val = ord (s) - ord (' 0' )
19
+ ret = ret * 10 + val
20
+ else :
21
+ if not flag:
22
+ if s == ' +' and k == 0 : # 避免中间出现+、-
23
+ flag = 1
24
+ elif s == ' -' and k == 0 :
25
+ flag = - 1
26
+ else :
27
+ raise Exception (' digit is need' , string)
28
+ else :
29
+ raise Exception (' digit is need' , string)
30
+ if flag and len (string) == 1 : # 判断是不是只有+、-
31
+ raise Exception (' digit is need' , string)
32
+ return ret if flag >= 0 else - ret
33
+ ```
You can’t perform that action at this time.
0 commit comments