8. 字符串转换整数 (atoi) @Python @Go

原题

https://leetcode.cn/problems/string-to-integer-atoi/description/

思路

字符串处理

复杂度

时间:O(n)
空间:O(n)

Python代码

class Solution:
    def myAtoi(self, s: str) -> int:
        flag = 1
        ans = 0
        isPrefix = True
        for i, ch in enumerate(s.strip()):
            if i == 0:
                if ch == "-":
                    flag = -1
                elif ch == "+":
                    continue
                elif ch.isdigit():
                    ans = ans * 10 + int(ch)
                    isPrefix = False
                else:
                    break
            else:
                if ch == "0" and isPrefix:
                    continue
                elif ch.isdigit():
                    ans = ans * 10 + int(ch)
                    isPrefix = False
                else:
                    break
            # 判断值是否溢出
            if ans * flag > 2**31 - 1:
                return 2**31 - 1
            elif ans * flag < -(2**31):
                return -(2**31)

        return min(max(ans * flag, -(2**31)), 2**31 - 1)

Go代码

func myAtoi(s string) int {
	// 符号
	flag := 1
	ans := 0
	isPrefix := true
    // 去除前导空格
    s = strings.TrimSpace(s)
	for i, ch := range s {
		if i == 0 {
			if string(ch) == "-" {
				flag = -1
			} else if string(ch) == "+" {
				continue
			} else if unicode.IsDigit(ch) {
				ans = ans * 10 + int(ch - '0')
				isPrefix = false
			} else {
				break
			}
		} else {
			if ch == '0' && isPrefix {
				continue
			} else if unicode.IsDigit(ch) {
				ans = ans * 10 + int(ch - '0')
				isPrefix = false
			} else {
				break
			}
		}
        // 判断值是否溢出
        if ans * flag > math.MaxInt32 {
            return math.MaxInt32
        } else if ans * flag < math.MinInt32 {
            return math.MinInt32
        }
	}
	return min(max(ans * flag, math.MinInt32), math.MaxInt32)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值