Leetcode JAVA刷刷站(8)字符串转换整数

 一、题目概述 

二、思路方向

    要实现这个功能,我们可以遵循以下步骤来编写 myAtoi 函数:

  1. 去除前导空格:使用循环或字符串的 trim() 方法(虽然直接操作字符串更高效的方式是使用循环)。
  2. 检查符号:记录第一个非空格字符是 '+'、'-' 还是数字,如果都不是则直接返回 0。
  3. 转换数字:从记录的起始位置开始,循环遍历字符串,将每个字符转换为数字,并累加到一个整数变量中。注意处理整数溢出的情况。
  4. 处理溢出:在累加过程中,检查当前结果是否超出了 32 位有符号整数的范围。

三、代码实现 

public class Solution {  
    public int myAtoi(String s) {  
        s = s.trim();  
        if (s.isEmpty()) return 0;  
  
        int index = 0;  
        int sign = 1;  
        long num = 0; // 使用 long 来避免在转换过程中溢出  
  
        // 检查符号  
        if (s.charAt(index) == '-') {  
            sign = -1;  
            index++;  
        } else if (s.charAt(index) == '+') {  
            index++;  
        }  
  
        // 转换数字  
        while (index < s.length() && Character.isDigit(s.charAt(index))) {  
            int digit = s.charAt(index) - '0';  
              
            // 检查溢出  
            if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && digit > 7)) {  
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;  
            }  
              
            num = num * 10 + digit;  
            index++;  
        }  
  
        return (int) (sign * num);  
    }  
  
    public static void main(String[] args) {  
        Solution solution = new Solution();  
        System.out.println(solution.myAtoi("   -42")); // 输出 -42  
        System.out.println(solution.myAtoi("4193 with words")); // 输出 4193  
        System.out.println(solution.myAtoi("words and 987")); // 输出 0  
        System.out.println(solution.myAtoi("-91283472332")); // 输出 -2147483648  
    }  
}

执行结果:

四、小结 

       这个实现中,我们首先去除了前导空格,然后检查了可能的符号位,之后通过一个循环将字符串中的数字字符转换为整数,并在过程中检查是否超过了 32 位整数的范围。注意,我们使用 long 类型来暂存结果,以防止在累加过程中发生溢出,直到最后才将其转换为 int 类型并返回。这样做可以确保在转换过程中能够检测到溢出情况,并根据符号返回相应的最大或最小值。

 结语 

路漫漫其修远兮

吾将上下而求索

!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT 青年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值