【LeetCode-Java实现】8. String to Integer (atoi)

8. String to Integer (atoi)

题目描述

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:(空格复制的时候没了,看leetcode官网吧)
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. 若字符串是空串,或没法转换就直接返回0
  2. 第一个非空格的元素若是正负号或者数字就可以继续向下找数字;
    若第一个非空元素不是那三者之一,就无法转换,直接返回0
  3. 若最后找到的数字太大(超过Int范围),就直接输出Int范围的最大(小)值

思路

  1. 去掉字符串中的空格,得到新字符串str1
  2. 创建个新字符串str2用来接收想得到的整型数
  3. 找到str1的首元素,判断是否属于正负号或数字,若属于,就把首元素加入到str2
    接着寻找后面的数字,并把这些数字加入到str2中——至此str2基本就有了
  4. 先判断str2可能出现的特殊情况:str2是空串/str2里面只有"+"或“-” ,这些属于无法转换的情况,直接返回0
  5. 将字符串转换为整数,利用Java的异常处理机制来处理得到的数字超出int范围的情况

(很多人用正则表达式,但我对正则表达式不熟,所以采用了上述思路)

实现

class Solution {
    public int myAtoi(String str) {
        //去空格
        String str1=str.trim();
        //定义一个String变量用来存储只含正负号和数字的字符串(最后再转换为Integer类型)
        String str2=null;
        
        //确保不是空串时找第一个非空元素:为正负号或者数字才能继续
        if(!str1.isEmpty() && str!=null){
            char f=str1.charAt(0);
            if(f=='+' || f=='-' || (f>='0' && f<='9')){
                str2=str1.substring(0,1);  //把第一位放入str2
                //接下来找数字,是数字就挂到str2上
                for(int i=1;i<str1.length();i++){
                    char c=str1.charAt(i);
                    if(c>='0' && c<='9'){
                        str2=str1.substring(0,i+1);
                    }
                    else{   //如果不是数字就跳出循环!!!
                        break;
                    }
                 }
            }    
        }
        
    
        
        //判断特殊情况————str2是空串/str2里面只有正负号,没有数字.....没法转换就返回0
        if(str2==null || str2.equals("+") || str2.equals("-")){    
                                                           //这里的"+""-"要有双引号,因为是字符串的比较!用单引号会报错
            return 0;
        }
        
        
        //将字符串转换为整型数-----利用Java的异常机制检测溢出int类型范围的情况!!!
        int num=0;
        try{
            num=Integer.parseInt(str2);   //未溢出int范围时
        }catch(Exception e){
            if(str2.charAt(0)=='-'){      //溢出后的异常处理
                return Integer.MIN_VALUE;
            }
            else{
                return Integer.MAX_VALUE;
            }
        }
        return num;  
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值