字符串转换整数

字符串转换整数

1、题目

image-20231222145709687

2、题解

方法1:使用已有函数去除字符串中的空格,然后再进行拼接

根据题意,有以下四种字符需要考虑:

首部空格: 先用strip()函数进行处理 符号位: 三种情况,即 ''+'' , ''−'' , ''无符号" ;新建一个变量保存符号位flag,返回前判断正负即可。 非数字字符: 遇到首个非数字的字符时,应立即返回。 数字字符:

  • 字符转数字: “此数字的 ASCII 码” 与 “ 0 的 ASCII 码” 相减即可。

  • 数字拼接: 若从左向右遍历数字,设当前位字符为 ind ,当前位数字为 x ,数字结果为 res,则数字拼接公式为: \[ \begin{aligned}res&=10\times res+x\\x&=ascii(ind)-ascii('0')\end{aligned} \]

数字越界处理:需要判断res在每轮拼接前先判断在此轮拼接后是否产生了越界,一共有两种情况。

第一种情况是res本身直接超过限定条件,第二种情况是res等于限定条件除去个位的范围,拼接的个位数大于限定条件所需的个位数(bndry=2147483647//10 = 214748364): \[ \begin{cases}res>bndry\\res=bndry,x>7&\end{cases} \]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip()
if not s : return 0
res, i, flag =0,1,1
int_max, int_min, boundary = 2**31-1, -2**31, 2**31//10

if s[0] == '-': flag=-1
elif s[0] !='+': i=0

for ind in s[i:]:
if not '0'<= ind <='9': break

if res>boundary or res==boundary and ind > '7': return int_max if flag==1 else int_min

res = res *10 + ord(ind) - ord('0')

return flag*res

方法2:使用遍历手动去除空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def myAtoi(self, s: str) -> int:
res, i, flag, length = 0, 0, 1, len(s)
int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
if not s: return 0 # 空字符串,提前返回
while s[i] == ' ':
i += 1
if i == length: return 0 # 字符串全为空格,提前返回
if s[i] == '-': flag = -1
if s[i] in '+-': i += 1
for j in range(i, length):
if not '0' <= s[j] <= '9' : break
if res > bndry or res == bndry and s[j] > '7':
return int_max if sign == 1 else int_min
res = 10 * res + ord(s[j]) - ord('0')
return flag * res

字符串转换整数
http://example.com/2023/12/22/字符串转换整数/
作者
Z Z
发布于
2023年12月22日
许可协议