字符串转换整数 (atoi) (String to Integer (atoi))

 

思路:

// @Title: 字符串转换整数 (atoi) (String to Integer (atoi))
// @Author: qisiii
// @Date: 2024-04-11 21:53:06
// @Runtime: 1 ms
// @Memory: 41.5 MB
// @comment: 
// @flag: 
class Solution {
    public int myAtoi(String s) {
        if (s.length() <= 0) {
            return 0;
        }
        s = s.trim();
        int result = 0, old = 0;
        boolean flag = false;
        int b = 1;
        for (char c : s.toCharArray()) {
            if (c >= '0' && c <= '9') {
                 flag = true;
                result = result * 10 + (c - '0');
                if ((result - (c - '0')) / 10 != old) {
                    if (b <0) {
                        return Integer.MIN_VALUE;
                    }
                    return Integer.MAX_VALUE;
                }
                 if (result<0&&b >0) {
                        return Integer.MAX_VALUE;
                    }else if(result<0&&b<0){
                        return Integer.MIN_VALUE;
                    }
                old = result;
            } else if (result > 0 || flag) {
                break;
            } else {
                if (c != '+' && c != '-') {
                    return 0;
                } else {
                    flag = true;
                }
                if (c == '-') {
                    b = -1;
                }
                continue;
            }
        }
        return b * result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18