LeetCode 08 字符串转换为数字

8. String to Integer (atoi)    难度:Medium

Implement atoi which converts a string to an integer.

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.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

题目很长,懒得看,,直接看例子就可以了。

例1 输入 42                            输出42

例2 输入 -42                           输出-42

例3 输入 4193 with words       输出 4193

例4 输入 words and 987         输出 0

例5 输入 -91283472332         输出 -2147483648

看完这几个例子,也就知道大概意思了,就是要把 字符串转换为数字,其中有几个规则:

1. 对于字符串首字符 不是 '+'  '-' 或者 数字的 ,返回 0;

2. 如果是数字,一直遍历下去,直到碰到一个非数字为止;

3. 对于值超出 int 类型范围的,返回 int 最大值 或 最小值。

实现:

package pers.leetcode;

/**
 * LeetCode 08 字符串转整数
 * 难度: Medium
 *
 * @author 朱景辉
 * @date 2019/3/20 10:35
 */
public class StringToInteger {
    public static void main(String[] args) {
        String s = "3232 323dsa sdfsa  ";
        System.out.println(myAtoi(s));
    }

    /**
     * 字符串转换为整数
     *
     * @param str 字符串
     * @return 整数
     */
    public static int myAtoi(String str){
        int result = 0;
        // 先去除字符串两端的所有空格
        str = str.trim();
        char[] chars = str.toCharArray();
        boolean isNegative = false;
        for (int i=0; i<str.length(); i++){
            // 先判断字符串的第一个字符 讨论 3 种情况
            // 1. '-' 表明是负数,做个标记
            // 2. '+' 显示表明是整数,继续遍历下一个字符
            // 3. 在 0 - 9 之间,结果保存下来
            // 4. 其余所有情况表明不能转换为整数,直接退出!
            if (i == 0){
                if (chars[i] == '-'){
                    isNegative = true;
                }else if(chars[i] >= '0' && chars[i] <= '9'){
                    result = result*10 + (chars[i] - '0');
                }else if(chars[i] == '+'){
                    continue;
                }else {
                    break;
                }
            }else {
                // 从第二个字符开始遍历,分两种情况
                // 1. 字符在 0 - 9 之间,又分 3 种情况
                //    1.1 正数情况下,判断是否大于 int 类型最大值,若超出,返回 int 型最大值
                //    1.1 负数情况下,判断是否小于 int 类型最小值,若小于,返回 int 型最小值
                //    1.3 其余情况下,均 * 10 再加当前字符对应的数值
                // 2. 其余字符直接退出
                if (chars[i]>='0' && chars[i]<='9'){
                    if ((!isNegative) && (result > Integer.MAX_VALUE / 10 || result == Integer.MAX_VALUE / 10 && (chars[i] - '0' > 7))){
                        return Integer.MAX_VALUE;
                    }
                    if (isNegative && (-1 * result < Integer.MIN_VALUE / 10 || (-1 * result == Integer.MIN_VALUE / 10 && (chars[i] - '0' > 8)))){
                        return Integer.MIN_VALUE;
                    }
                    result = result*10 + (chars[i] -'0');
                } else {
                    break;
                }
            }
        }
        if (isNegative){
            return -1 * result;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33378853/article/details/88683908
今日推荐