[LeetCode]String to Integer (atoi)

本文详细解析了如何将一个字符串转换为整数的过程,包括去除前导空格、检查符号、验证数字溢出等关键步骤,并提供了一个Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要是一下步骤

1.delete space in front of str

2.check if str startsWith other characters

3.check if str is positive

4.check the end of str

5.check if overflow

public class Solution {
    public int myAtoi(String str) {
        while (str.length() > 0 && str.charAt(0) == ' ') {
            str = str.substring(1);
        }
        if (str.length() == 0 || (str.charAt(0) != '+' && str.charAt(0) != '-' && !isNum(str.charAt(0)))) {
            return 0;
        }
        int positive = 1;
        if (str.charAt(0) == '+') {
            str = str.substring(1);
        } else if (str.charAt(0) == '-') {
            positive = -1;
            str = str.substring(1);
        }
        boolean flg = true;
        int i = 0;
        for (; i < str.length(); i++) {
            if (!isNum(str.charAt(i))) {
                flg = false;
                break;
            }
        }
        if (!flg) {
            str = str.substring(0, i);
        }
        if (str.length() > 11) {
            return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        if (str.length() == 0) {
            return 0;
        }
        Long tmp = Long.valueOf(str);
        if (tmp > Integer.MAX_VALUE) {
            return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        return Integer.valueOf(str) * positive;
    }
    public boolean isNum(char c) {
        return c <= '9' && c >= '0';
    }
}

 

转载于:https://www.cnblogs.com/vision-love-programming/p/5020974.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值