8. String to Integer (atoi) leetcode算法笔记

来源:互联网 发布:水果淘宝店店名大全 编辑:程序博客网 时间:2024/05/29 03:38

Implement atoi to convert a string to an integer.



step1.去掉空格;

step2.判断±号;

step3.依次遍历,如果为0~9,则base*10加上该数字,将得到的值赋给base。若base大于214746364,或等于214746364并且该数字大于7,说明int溢出,返回2147463647或2147463648;

step4.返回base*sign。


具体代码:

public int myAtoi(String str) {        if (str.isEmpty()) return 0;        int sign = 1, base = 0, i = 0;        while (str.charAt(i) == ' ') i++;        if (str.charAt(i) == '-' || str.charAt(i) == '+') sign = str.charAt(i++) == '-' ? -1 : 1;        while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;            }            base = 10 * base + (str.charAt(i++) - '0');        }        return base * sign;    }


0 0