Problem 8

Posted by Ruizhi Ma on July 12, 2019

问题描述

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

解决思路

直接看代码吧,题目就是有点麻烦,不是很难,注释把思路写的够清晰了

代码

class Solution {
    public int myAtoi(String str) { 
        //process the whitespace
        str = str.trim();
        
        //corner case
        if(str == null || str.length() == 0) return 0;
        
        char firstChar = str.charAt(0);
        long res = 0;
        int isPositive = 1;
        int start = 0;
        
        //process '+'/'-' occcurs in the begining
        if(firstChar == '+') {
            isPositive = 1;
            start++;
        } else if(firstChar == '-'){
            isPositive = -1;
            start++;
        }
        
        for(int i = start; i < str.length(); i++){
            if(!Character.isDigit(str.charAt(i))){
                return (int)(isPositive * res);
            }
            //count the res
            res = res * 10 + (str.charAt(i) - '0');
            
             //out the range
            if(isPositive == 1 && res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if(isPositive == -1 && res > Integer.MAX_VALUE) return Integer.MIN_VALUE;
        }
        return (int)(isPositive * res);
    }
}

效率探究

时间效率:O(n)
空间效率:O(1)