个人记录-LeetCode 8.String to Integer (atoi)

本文介绍了一个简单的字符串转整数(atoi)的实现方法,包括处理可能的输入情况,如空格、正负号及非数字字符等,并提供了一个Java代码示例,展示了如何有效地解析字符串并将其转换为整数。

问题
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

思路极其简单,但没有约定何为真正有效的输入,实际上只能试错然后修改。
在现在这个时间点,服务器认为一个有效的字符串在前面可以出现空格;从非空格开始,可以用”+”、“-”后必须立即连接实际的数字。

代码示例:

public class Solution {
    public int myAtoi(String str) {
        if (str == null) {
            return 0;
        }

        char[] sChar = str.toCharArray();
        int len  = sChar.length;
        if (len <= 0) {
            return 0;
        }

        int beginIndex = 0;
        //跳过空格
        for (int i = 0; i < len; ++i) {
            if (sChar[i] == ' ') {
                ++beginIndex;
            } else {
                break;
            }
        }

        boolean negative = false;
        //判断是否以+、-号开头
        if (sChar[beginIndex] == '-') {
            negative = true;
            ++beginIndex;
        } else if (sChar[beginIndex] == '+') {
            ++beginIndex;
        }

        long result = 0;
        for (int i = beginIndex; i < len; ++i) {
            int temp = sChar[i] - '0';
            //判断是否为数字,不是的话则结束解析
            if (temp >=0 && temp <=9) {
                result = result * 10 + temp;

                if (result > Integer.MAX_VALUE) {
                    if (negative) {
                        return Integer.MIN_VALUE;
                    } else {
                        return Integer.MAX_VALUE;
                    }
                }
            } else {
                break;
            }
        }

        if (negative) {
            result *= -1;
        }

        return (int)result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值