LeetCode题解——字符串转整数(atoi)

LeetCode题解——字符串转整数(atoi)

我的LeetCode代码集:https://github.com/cnamep001/LeetCode

原题链接:https://leetcode-cn.com/problems/string-to-integer-atoi/description/



题目描述:

img

知识点:字符串




思路:顺序遍历字符串,根据题意读取整数

对于这一题来说,难点不在算法的实现上,难点在理解题意并正确处理各种边界或者特殊情况上。

(1)如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即为整数的值。

(2)如果第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

(3)如果第一个非空字符既不是正号或负号,也不是数字,返回0。

(4)如果字符串为空,或者字符串内只包含空字符,返回0。

(5)如果第一个非空字符是正号或负号,但接下来的第二个字符不是数字,返回0。对于"+-2"、"+ 2"这两种情况,都返回0。

(6)如果数值超过可表示的范围 [−2^31, 2^31 − 1],则返回 INT_MAX (2^31 − 1) 或 INT_MIN (−2^31) 。实现时用Integer.valueOf()函数抛出的异常来判断整数越界

注意:字符比较要用"==",但字符串比较要用equals()方法。

时间复杂度和给的字符串中第一个空白字符出现的位置,以及其后或者第一个正负号其后连续的数字个数有关,但一定是小于O(n)时间复杂度的,其中n为字符串的长度。空间复杂度和时间复杂度相同。



代码如下:

package com.m.string_to_integer_atoi;


public class Solution1 {

    public int myAtoi(String str) {
        int n = str.length();
        int i = 0;
        while(i < n && str.charAt(i) == ' ') {
            i++;
        }
        if(i == n || !((str.charAt(i) == '+') || (str.charAt(i) == '-') ||(str.charAt(i) >= '0' && str.charAt(i) <= '9'))) {
            return 0;
        }
        StringBuilder stringBuilder = new StringBuilder();
        if(str.charAt(i) == '-') {
            stringBuilder.append('-');
            i++;
        }else if(str.charAt(i) == '+') {
            i++;
        }
        if(i == n || !(str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
            return 0;
        }
        while(i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            stringBuilder.append(str.charAt(i));
            i++;
        }
        try {
            return Integer.valueOf(stringBuilder.toString());
        }catch (Exception e) {
            if(stringBuilder.substring(0, 1).equals("-")) {
                return Integer.MIN_VALUE;
            }else {
                return Integer.MAX_VALUE;
            }
        }
    }

}



LeetCode解题报告:

测试代码:

package com.m.string_to_integer_atoi;


public class Test1 {
    public static void main(String[] args) {
        String [] strings = new String[]
                {"  42 "," -4 2", " 4 hello 2 world","hello 42","-91283472332"};
        Solution1 solution1 = new Solution1();
        int temp;
        for (int i = 0; i <strings.length ; i++) {
            System.out.print("字符串是:"+strings[i]+"	");
            temp = solution1.myAtoi(strings[i]);
            System.out.println("结果是:"+temp);
        }
    }
}

原文地址:https://www.cnblogs.com/k-class/p/13796494.html