题目主要信息

1、将字符串转换成整数

2、去掉无用空格

3、判断正负值

4、只取有效数字

5、防止溢出

方法一:直接转换

具体方法

我们根据题意,只需要处理以下几种情况 1、首位空格:通过trim()函数即可处理 2、正负:通过判断第一位,使用变量储存符号即可 3、非数字字符:对每一位进行判断,非数字则结束 4、越界:通过提前预判,判断拼接后是否大于阈值,进行处理 alt

Java代码

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int StrToInt (String s) {
        // write code here
        char[] array = s.trim().toCharArray();
        if(array.length==0){
            return 0;
        }
        int sign = 1;
        int res = 0;
        int i = 0;
        
        if(array[i] == '+' || array[i] == '-'){
            sign = array[i++] == '+' ? 1 : -1;
        }
        while(i < array.length){
            char cur = array[i];
            if(cur < '0' || cur>'9'){
                break;
            }
            if (res >= Integer.MAX_VALUE / 10) {
                if(res > Integer.MAX_VALUE / 10){
                    return sign==1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                if(res == Integer.MAX_VALUE / 10){
                    if(sign == 1 && (cur - '0') > 7){
                        return Integer.MAX_VALUE;
                    }else if(sign == -1 && (cur - '0') > 8){
                        return Integer.MIN_VALUE;
                    }
                }
            }
            res = res * 10 + (cur - '0');
            i++;
        }
        return sign * res;
    }
}

复杂度分析

  • 时间复杂度:O(n)O(n),单层循环
  • 空间复杂度:O(n)O(n),构建一维数组与trim()函数

方法二:优化空间复杂度

具体方法

上述方法的空间复杂度为O(n)O(n),主要因为构建一维数组与trim()函数,这里可以进行优化。

Java代码

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int StrToInt (String s) {
        // write code here
        int sign = 1;
        int res = 0;
        int i = 0;
        while(i<s.length() && s.charAt(i)==' '){
            i++;
        }
        if(i==s.length()){
            return 0;
        }
        if(s.charAt(i) == '+' || s.charAt(i) == '-'){
            sign = s.charAt(i++) == '+' ? 1 : -1;
        }
        while(i < s.length()){
            char cur = s.charAt(i);
            if(cur < '0' || cur>'9'){
                break;
            }
            if (res >= Integer.MAX_VALUE / 10) {
                if(res > Integer.MAX_VALUE / 10){
                    return sign==1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                if(res == Integer.MAX_VALUE / 10){
                    if(sign == 1 && (cur - '0') > 7){
                        return Integer.MAX_VALUE;
                    }else if(sign == -1 && (cur - '0') > 8){
                        return Integer.MIN_VALUE;
                    }
                }
            }
            res = res * 10 + (cur - '0');
            i++;
        }
        return sign * res;
    }
}

复杂度分析

  • 时间复杂度:O(n)O(n),单层循环
  • 空间复杂度:O(1)O(1)