字符串的转换leetcode(8)

1.这个题其实不难,但是涉及到好多小的知识点,边界条件之类的。所以实现起来有点费劲。其实自己也想到了就是不会敲代码,还是基础知识不够扎实。一点一点积累吧。

public class Solution {

    public int myAtoi(String str) {
        int len = str.length();

        // 去除前导空格
        int index = 0;
        while (index < len) {
            if (str.charAt(index) != ' ') {
                break;
            }
            index++;
        }

        if (index == len) {
            return 0;
        }

        // 第 1 个字符如果是符号,判断合法性,并记录正负
        int sign = 1;
        char firstChar = str.charAt(index);
        if (firstChar == '+') {
            index++;
            sign = 1;
        } else if (firstChar == '-') {
            index++;
            sign = -1;
        }

        // 不能使用 long 类型,这是题目说的
        int res = 0;
        while (index < len) {
            char currChar = str.charAt(index);
            // 判断合法性
            if (currChar > '9' || currChar < '0') {
                break;
            }

            // 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判断乘以 10 以后是否越界
            if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
                return Integer.MAX_VALUE;
            }
            if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
                return Integer.MIN_VALUE;
            }

            // 每一步都把符号位乘进去
            res = res * 10 + sign * (currChar - '0');
            index++;
        }

        return res;
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/jin-liang-bu-shi-yong-ku-han-shu-nai-xin-diao-shi-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

结论:
1.其实判断int是否越界是不用这么麻烦的,这里是因为最终的结果是不断变化的,所以么一次得到当前最终结果的时候都要进行判断是否越界,如果越界了就不会进行下一步的组装,直接给出返回值。如果有多个变量,保留当前的和之前的结果,那么也可以不用这么麻烦的。但是代码还是题解中给出的是最简洁的。

if(resault>Integer.MAX_VALUE||resault<Integer.MIN_VALUE) {
    System.out.println("发生溢出");
}

2.想得到当前数字字符对应的数字时,可以直接进去’0’字符,这样就得到了对应的数字。
3.还有就是直接对当前字符与‘0’‘9’字符进行比较就行了,不需要先变成数字在比较,因为不变符合要求的就不会进行接下来的操作。

也可以用正则表达式来做
正则表达式

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值