2021-03-12 数据结构 67. 把字符串转换成整数

image.png

image.png
  1. 删除空格并判定字符串是否为空
  2. 定义以及表达边界
  3. 考虑符号
  4. 遍历

字符串不能直接运算,要转化ASCII码

class Solution:
    def strToInt(self, str: str) -> int:
        str = str.strip()                      # 删除首尾空格
        if not str: return 0                   # 字符串为空则直接返回
        res, i, sign = 0, 1, 1
        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
        if str[0] == '-': sign = -1            # 保存负号
        elif str[0] != '+': i = 0              # 若无符号位,则需从 i = 0 开始数字拼接
        for c in str[i:]:
            if not '0' <= c <= '9' : break     # 遇到非数字的字符则跳出
            if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理
            res = 10 * res + ord(c) - ord('0') # 数字拼接
        return sign * res

字符串转数字 用ASCII码减去0的ASCII码 ord(c) - ord('0')

不使用strip()

class Solution:
    def strToInt(self, str: str) -> int:
        res, i, sign, length = 0, 0, 1, len(str) 
        int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
        if not str: return 0         # 空字符串,提前返回
        while str[i] == ' ':   #不使用strip剔除空格则加while循环将i增加
            i += 1
            if i == length: return 0 # 字符串全为空格,提前返回
        if str[i] == '-': sign = -1
        if str[i] in '+-': i += 1   
        for j in range(i, length):
            if not '0' <= str[j] <= '9' : break
            if res > bndry or res == bndry and str[j] > '7':
                return int_max if sign == 1 else int_min
            res = 10 * res + ord(str[j]) - ord('0')
        return sign * res
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容