leetcode 8. 字符串转换整数 (atoi)

https://leetcode-cn.com/problems/string-to-integer-atoi/

class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        char[] cArr = str.toCharArray();
        if(cArr.length<1){
            return 0;
        }
        boolean positive = true;
        if(cArr[0]=='-'){
            positive = false;
            cArr[0] = '0';
        } else if(cArr[0]=='+'){
            cArr[0] = '0';
        }
        
        long result = 0L;
        for (int i = 0; i < cArr.length; i++) {
            if (cArr[i] >= '0' && cArr[i] <= '9') {
                result=result*10+cArr[i]-'0';
            } else {
                break;
            }
            if (positive && result > Integer.MAX_VALUE) {
                result = Integer.MAX_VALUE;
                break;
            } else if (!positive && result > Integer.MAX_VALUE + 1L) {
                result = Integer.MAX_VALUE + 1;
                break;
            }
        }
        return positive ? (int)result : -1 * (int)result;
    }
}

你可能感兴趣的:(算法研究)