LeetCode 8. String to Integer (atoi) 原创Java参考解答

LeetCode 8. String to Integer (atoi) 原创Java参考解答

问题描述

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

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

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.

解题思路

题目是实现把字符串转换为整数的atoi函数。

atoi函数的要求:

  • 返回类型为int类型,若字符串越界,则返回Integer.MAX_VALUE或Integer.MIN_VALUE.
  • 开头是+返回正数;-返回负数。例如“+23”返回23;“-42”返回-42。
  • 开头不是数字,则返回0:“fw923”和“+se243”都返回0。
  • 若开头为空格,则忽略空格:“ 233”返回233。
  • 只取连续的数字:“233pp233”返回的是233而不是233233。

这道题实现代码上并没有太大思维困难,只需按要求处理上述情况即可。可以按字符遍历顺序实现代码,先处理空格情况、再正负号判定、最后处理越界问题。

参考代码

public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        
        long result = 0;
        
        int start = 0;
        boolean isNegative = false;
        
        // discards whitespace characters before the number 
        for (int i = start; i < str.length(); i++) {
            if (str.charAt(i) != ' ') {
                break;
            }        
            start++;
        }
        
        // check if the string start with '+' or '-'
        if (str.charAt(start) == '-' || str.charAt(start) == '+') {
            if (str.charAt(start) == '-') {
                isNegative = true;
            }
            start++;
        }
        
        for (int i = start; i < str.length(); i++) {
            // terminates if non-numerical character appears
            if (!Character.isDigit(str.charAt(i))) {
                break;
            }
            result = result * 10 + (long)(str.charAt(i) - '0');

            // if positive, check if number out of integer upper bound
            if (!isNegative && result > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            
            // if negative, check if number out of integer lower bound
            if (isNegative && (-1) * result < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;            
            }
        }
        
        result = isNegative == true ? -result : result;
        return (int)result;
    }
}

相关题目

LeetCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注