LeetCode 0008 字符串转换整数atoi(Java)

写在前面:
本人小白,刷LeetCode,练习算法和写程序的感觉,在此做简单记录。若有不当之处,欢迎留言交流。

/**
 * LeetCode 0008 字符串转换整数atoi
 * author: MammothKan
 * time: 2020/4/29
 * 题目描述:https://leetcode-cn.com/problems/string-to-integer-atoi/
 * 解题思路:
 *      1. 去除字符串的前部空白字符
 *      2. 判断首字符为“+”、“-”、数字 或 其它字符,并给出对应的plusMinus和startIndex
 *      3. 遍历字符串result = result*10 + digit,直到遇到非数字字符结束
 *      4. int边界问题,要求每次运算都满足Integer.MAX_VALUE > result*10 + digit。
 *          正向思维中,先计算result,再判断大小,但是在程序中当result*10 + digit溢出时,便会报错。
 *          采用逆向思维,Integer.MAX_VALUE > result*10 + digit 可以转会为 (Integer.MAX_VALUE - digit) / 10 > result 依此来判断。
 */

public class L0008字符串转换整数atoi {

    public int myAtoi(String s) {
        if (s.length() == 0) {
            return 0;
        }
        //1. 去除字符串的前部空白字符
        s = s.trim();
        char[] cArray = s.toCharArray();
        char firstChar = cArray[0];
        boolean plusMinus;
        int startIndex;
        //2. 判断首字符为“+”、“-”、数字 或 其它字符,并给出对应的plusMinus和startIndex
        if (firstChar == '-'){
            plusMinus = false;
            startIndex = 1;
        }
        else if (firstChar == '+'){
            plusMinus = true;
            startIndex = 1;
        }
        else if (Character.isDigit(firstChar)) {
            plusMinus = true;
            startIndex = 0;
        }
        else {
            return 0;
        }
        //3. 遍历字符串result = result*10 + digit,直到遇到非数字字符结束
        int result = 0;
        for (int i=startIndex; i<cArray.length; i++) {
            if (Character.isDigit(cArray[i])) {
                int digit = cArray[i]-'0';
                //4. 溢出处理
                int resultMax = (Integer.MAX_VALUE - digit) / 10;
                if (resultMax < result) {
                    return plusMinus ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                else {
                    result = result*10 + digit;
                }
            }
            else {
                break;
            }
        }
        return plusMinus ? result : -1*result;
    }

    public static void main(String[] args) {
        System.out.println(new L0008字符串转换整数atoi().myAtoi("fsd       42"));
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值