8. String to Integer (atoi)

Description

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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Solution

I think we only need to handle four cases:

  • discards all leading whitespaces
  • sign of the number
  • overflow, return MAX_VALUE or MIN_VALUE base on the sign
  • invalid input, read as many valid characters as possible, and discard the following chars.
class Solution {
    public int myAtoi(String str) {
        if (str == null) {
            return 0;
        }
        
        long val = 0;
        char[] arr = str.trim().toCharArray();
        boolean isPositive = true;
        int i = 0;

        if (i < arr.length && (arr[i] == '+' || arr[i] == '-')) {
            isPositive = arr[i] == '+';
            ++i;
        }
        
        while (i < arr.length) {
            char c = arr[i];
            if (c < '0' || c > '9') {
                break;
            }
            
            val = val * 10 + (c - '0');

            if (isPositive && val > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;    // return directly!
            } else if (!isPositive && -val < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
            
            ++i;
        }
        
        return isPositive ? (int) val : (int) -val;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容