字符串转整数

2018-04-20  本文已影响33人  Stroman

题目

实现 atoi,将字符串转为整数。
在找到第一个非空字符之前,需要移除掉字符串中的空格字符。如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即为整数的值。如果第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。
字符串可以在形成整数的字符后面包括多余的字符,这些字符可以被忽略,它们对于函数没有影响。
当字符串中的第一个非空字符序列不是个有效的整数;或字符串为空;或字符串仅包含空白字符时,则不进行转换。
若函数不能执行有效的转换,返回 0。
说明:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。如果数值超过可表示的范围,则返回 INT_MAX (231 − 1) 或 INT_MIN (−231) 。

示例 1:
输入: "42"
输出: 42

示例 2:
输入: " -42"
输出: -42
解释: 第一个非空白字符为 '-', 它是一个负号。
我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。

示例 3:
输入: "4193 with words"
输出: 4193
解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。

示例 4:
输入: "words and 987"
输出: 0
解释: 第一个非空字符是 'w', 但它不是数字或正、负号。
因此无法执行有效的转换。

示例 5:
输入: "-91283472332"
输出: -2147483648
解释: 数字 "-91283472332" 超过 32 位有符号整数范围。
因此返回 INT_MIN (−231) 。

思路

主要思路

主要思路有了,剩下的就是如何判断得到的数字是否越界了,可以看这篇博客的思路。

使用

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        String inputString0 = "42";
        String inputString1 = "   -42";
        String inputString2 = "4193 with words";
        String inputString3 = "words and 987";
        String inputString4 = "91283472332";
        String inputString5 = "";
        String inputString6 = "1";
        String inputString7 = "-2147483647";
        System.out.println(Solution.myAtoi(inputString3));
    }
}

输出

0

Process finished with exit code 0

实现

package com.company;

public class Solution {
    /**
     * @param inputString
     * @return
     */
    static public int myAtoi(String inputString) {
        if (inputString == null || inputString.length() == 0) {
            System.out.println("字符串为空");
            return 0;
        }
        int currentIndex = 0;
        while (inputString.charAt(currentIndex) == ' ' && currentIndex < inputString.length())
            currentIndex++;
        if (Solution.isTheEndOfString(inputString,currentIndex))return 0;
        int unsignedResultNumber = 0;
        int symbolFlag = 1;//符号位,默认为负号。
        if (inputString.charAt(currentIndex) == '-' ||
                inputString.charAt(currentIndex) == '+' ||
                (inputString.charAt(currentIndex) <= '9' && inputString.charAt(currentIndex) >- '0')) {
            if (inputString.charAt(currentIndex) == '-') {
                symbolFlag = -1;
                currentIndex++;
                if (Solution.isTheEndOfString(inputString,currentIndex)) {
                    return 0;
                } else {
                    return Solution.accumulationResult(currentIndex,inputString,symbolFlag,unsignedResultNumber);
                }
            } else if (inputString.charAt(currentIndex) == '+') {
                currentIndex++;
                if (Solution.isTheEndOfString(inputString,currentIndex)) {
                    return 0;
                } else {
                    return Solution.accumulationResult(currentIndex,inputString,symbolFlag,unsignedResultNumber);
                }
            } else {
                return Solution.accumulationResult(currentIndex,inputString,symbolFlag,unsignedResultNumber);
            }
        } else {
            return 0;
        }
    }

    /**
     * 根据输入的字符串,符号位,当前的下标计算最后的结果值。
     * 除此之外还判断了是否越界。
     * @param currentIndex
     * @param inputString
     * @param symbolFlag
     * @param unsignedResultNumber
     * @return
     */
    static private int accumulationResult(int currentIndex,
                                          String inputString,
                                          int symbolFlag,
                                          int unsignedResultNumber) {
        int criticalValue = 0;
        int singleDigit = 0;
        if (symbolFlag < 0) {
            criticalValue = Integer.MIN_VALUE / 10;
            singleDigit = criticalValue * 10 - Integer.MIN_VALUE;
            criticalValue = -criticalValue;
        } else {
            criticalValue = Integer.MAX_VALUE / 10;
            singleDigit = Integer.MAX_VALUE - criticalValue * 10;
        }
        while (currentIndex < inputString.length()
                && inputString.charAt(currentIndex) <= '9'
                && inputString.charAt(currentIndex) >= '0') {
            if (unsignedResultNumber > criticalValue) {
                if (symbolFlag > 0)return Integer.MAX_VALUE;
                else return Integer.MIN_VALUE;
            } else if (unsignedResultNumber == criticalValue) {
                unsignedResultNumber *= 10;
                int currentSingleDigit = Solution.getIntFromCharacter(inputString.charAt(currentIndex));
                if (currentSingleDigit >= singleDigit) {
                    if (symbolFlag < 0)return Integer.MIN_VALUE;
                    else return Integer.MAX_VALUE;
                } else {
                    unsignedResultNumber += currentSingleDigit;
                    return symbolFlag * unsignedResultNumber;
                }
            } else {
                unsignedResultNumber *= 10;
                unsignedResultNumber += Solution.getIntFromCharacter(inputString.charAt(currentIndex));
            }
            currentIndex++;
        }
        return symbolFlag * unsignedResultNumber;
    }

    /**
     * 判断当前字符是否已经是最后一个字符了?
     * @param sourceString
     * @param currentIndex
     * @return
     */
    static private boolean isTheEndOfString(String sourceString,
                                            int currentIndex) {
        if (sourceString.length() < currentIndex + 1)return true;
        else return false;
    }

    /**
     * 从输入的数字字符获取真正的数字
     * @param inputChar
     * @return
     */
    static private int getIntFromCharacter(char inputChar) {
        if (inputChar < '0' || inputChar > '9')return 0;
        return inputChar - '0';
    }
}

上一篇下一篇

猜你喜欢

热点阅读