LeetCode - 解题笔记 - 8 - String to Integer (atoi)

String to Integer (atoi)

Solution 1

这个题和Question 6其实考察的内容一样,都是对整数的按位处理,以及溢出时的额外判断。因为都是上一个题有过的策略,因此在这里不做详细描述了。根据本题的额外要求,就是要判断数字前面是否只有空格字符,以及没有有效数字的情形。

  • 时间复杂度: O ( n ) O(n) O(n) n n n为字符串到数字结尾的长度
  • 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个变量
class Solution {
public:
    int myAtoi(string s) {
        
        int ans = 0;
        int pos = 0;
        bool plus = true;
        
        // whitespace
        while (pos < s.size() && s.at(pos) == ' ') {
            pos ++;
        }
        
        if (pos >= s.size()) {
            // all whitespaces
            return 0;
        }
        else if (s.at(pos) != '+' && s.at(pos) != '-' && s.at(pos) < '0' && s.at(pos) > '9') {
            // first non-whitespce is not a number or sign
            return 0;
        }
        
        // sign
        if (s.at(pos) == '+' || s.at(pos) == '-') {
            plus = s.at(pos) == '+' ? true : false;
            pos ++;
        }
        
        while (pos < s.size() && s.at(pos) >= '0' && s.at(pos) <= '9') {
            int current = s.at(pos) - 48;
            // overflow?
            if (ans > INT_MAX / 10 || (ans == INT_MAX / 10 && current > 7)) {
                return plus? INT_MAX : INT_MIN;
            }
            ans = ans * 10 + current;
            pos ++;
        }
        
        if (!plus) {
            ans *= -1;
        }
        
        return ans;
    }
};

Solution 2

Solution 1的Python实现,这里不需要对负数取余,因此没有特别多的注意事项,此外Python有很多非常方便的字符串处理函数。

class Solution:
    def myAtoi(self, s: str) -> int:
        # whitespace
        s = s.strip()
        
        if len(s) == 0:
            return 0
        
        # other non-whitespace character
        if s[0] != '+' and s[0] != '-' and not s[0].isdigit():
            return 0
        
        sign = True
        ans = ''
        # sign
        if s[0] == '+' or s[0] == '-':
            sign = True if s[0] == '+' else False
            s = s[1:]
            
        for c in s:
            if not c.isdigit():
                break;
            else:
                ans += c
            
        if len(ans) == 0:
            return 0
                
        ans = int(ans)
        if not sign:
            ans *= -1
            
        if ans > 2**31 -1 or ans < 2 ** 31 * -1:
            ans = 2**31 -1 if ans > 2**31 -1 else 2**31 * -1
            
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值