美文网首页LeetCode
[LeetCode] 8. String to Integer

[LeetCode] 8. String to Integer

作者: xxx亦凡桑 | 来源:发表于2017-05-05 08:52 被阅读0次

    Implement atoi to convert a string to an integer.

    Hint:
    Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes:
    It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.


    </br>

    Solution

    atoi, which means alphanumeric to integer, requires the function to input a string of numbers and convert it into an integer.

    In order to do that, we first have to ignore all the blank spaces and start outputting integer once encountering the first non-blank characters. Also, the sign of the string should also be taken care of. Once we hit the decimal point or next blank space, the output will be terminated.

    To achieve the requirement above, we have to consider all the possible inputs. Firstly, we should consider the empty string or a string of all blanks, either way we should return 0. Additionally, even if the string is valid, we should still return 0 when no valid conversion is available. Finally, when the output overflows, we should return the MAX_INT or MIN_INT.

    To get specific digit at any given position, we can use charAt( ) function.

    The code is shown as below.

    Java

    public class Solution {
        public int myAtoi(String str) {
            
            int index = 0, current = 0, sign = 1; 
            long output = 0;
            
            //empty
            if (str.length() == 0)
                return 0;
                
            while (index < str.length() && str.charAt(index) == ' ')
                index ++;
            
            //all blank spaces    
            if (index >= str.length())
                return 0;
                
            //sign
            if (str.charAt(index) == '+' || str.charAt(index) == '-'){ //if there is no sign, then the output is positive.
                sign = str.charAt(index) == '+' ? 1 : -1; 
                index += 1;
            }
            
            while (index < str.length()){
                current = str.charAt(index) - '0';
                
                if (current < 0 ||current > 9)
                    break;
                
                output = output * 10 + current;
                index ++;
                
                if ((int)output != output)
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; 
            }
            return (int)output*sign;
            
        }
    }
    

    </br>

    相关文章

      网友评论

        本文标题:[LeetCode] 8. String to Integer

        本文链接:https://www.haomeiwen.com/subject/yddjtxtx.html