MENU

LeetCode8. 字符串转整数 (atoi)

July 8, 2018 • Read: 2647 • LeetCode阅读设置


多考虑一些细节即可

class Solution {
    public int myAtoi(String str) {
        long ans = 0,MAX_INT = (long)Integer.MAX_VALUE + 1;
        boolean flag = false;
        int st = 0;
        while(st < str.length() && str.charAt(st) == ' ') {
            st++;
        }
        if(st < str.length() && str.charAt(st) == '+')
            st++;
        else {
            if(st < str.length() && str.charAt(st) == '-') {
                st++;
                flag = true;
            }
        }
        for(int i = st;i < str.length();i++) {
            if(str.charAt(i) <= '9' && str.charAt(i) >= '0') {
                ans = ans * 10 + str.charAt(i) - '0';
                if(ans > MAX_INT)
                    ans = MAX_INT;
            }         
            else
                break;
        }
        if(flag)
            ans = -ans;
        if(ans > Integer.MAX_VALUE)
            ans = Integer.MAX_VALUE;
        if(ans < Integer.MIN_VALUE)
            ans = Integer.MIN_VALUE;
        return (int)ans;
    }
}
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment