Skip to content

Commit 110a8db

Browse files
committed
feat: string-to-integer-atoi
1 parent 3c87cd3 commit 110a8db

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

str.first-unique-character-in-a-string.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ def firstUniqChar(self, s: str) -> int:
1919

2020

2121
so = Solution()
22-
print(so.firstUniqChar('loveleetcode'))
22+
print(so.firstUniqChar('cc'))
23+
print('cc'.rfind('c'))

str.string-to-integer-atoi.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution:
2+
"""
3+
8. 字符串转换整数 (atoi)
4+
https://leetcode-cn.com/problems/string-to-integer-atoi
5+
请你来实现一个 atoi 函数,使其能将字符串转换成整数。
6+
7+
首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下:
8+
9+
如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。
10+
假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。
11+
该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。
12+
注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换,即无法进行有效转换。
13+
14+
在任何情况下,若函数不能进行有效的转换时,请返回 0 。
15+
"""
16+
def myAtoi(self, s: str) -> int:
17+
res = ''
18+
s = s.lstrip()
19+
sym = 1
20+
num = '0123456789'
21+
for i in range(len(s)):
22+
if i == 0 and s[i] == '+':
23+
continue
24+
elif i == 0 and s[i] == '-':
25+
sym = -1
26+
elif s[i] in num:
27+
res += s[i]
28+
else:
29+
break
30+
31+
if res == '':
32+
return 0
33+
34+
res = int(res) * sym
35+
if 2147483647 >= res >= - 2147483648:
36+
return res
37+
38+
if res >= 0:
39+
return 2147483647
40+
else:
41+
return -2147483648
42+
43+
so = Solution()
44+
print(so.myAtoi('words and 987'))

0 commit comments

Comments
 (0)