代码改变世界首页投稿(暂停使用,暂停投稿)

LeetCode 解题报告 - 8. String to Int

2016-10-12  本文已影响0人  秋名山菜车手

尼玛,我要被这道题的题目搞死了... 2016/10/12
编程语言是 Java,代码托管在我的 GitHub 上,包括测试用例。欢迎各种批评指正!

<br />

题目 —— String to Integer (atoi)

Implement atoi to convert a string to an integer.

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 os representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

<br >

解答

public class Solution {
    public int myAtoi(String str) {
        if (str.length() == 0) return 0;
        
        int i = 0, result = 0, sign = 1;
        // 跳过空字符
        while (i < str.length() && str.charAt(i) == ' ') {
            i++;
        }
        // 获取符号位
        if (str.charAt(i) == '+' || str.charAt(i) == '-') {
            sign = (str.charAt(i) == '+') ? 1 : -1;
            i++;
        }
        // 判断其他情况
        while (i < str.length()) {
            int digit = str.charAt(i) - '0';
            if (digit < 0 || digit > 9) break;
            if (Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE % 10 < digit) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            result = result * 10 + digit;
            i++;
        }
        return result * sign;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读