No.008 String to Integer (atoi)

时间:2022-04-29
本文章向大家介绍No.008 String to Integer (atoi),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

8. String to Integer (atoi)

  • Total Accepted: 112863
  • Total Submissions: 825433
  • Difficulty: Easy

  Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

  思路:

  本题的难度倒不大,主要是考察的细心程度和对和各种可能的情况是否考虑清楚。题主也是通过三四次提交失败之后才accepted。

  主要考虑的情况有以下几种:

  • 空串或str == null
  • 字符串开头有连续的空格
  • 非空格的第一个字符为“+”或“-”或0或其他情况
  • 字符串长度可能非常长,甚至转换过来之后超过long类型的范围
  • 当遇到非正常字符时,输出之前的结果,eg:-123a245,输出结果为-123
  • 对于输出结果超出int类型范围的输出边界值,也就是说输出结果大于int类型最大值,则输出Integer.MAX_VALUE,当输出结果小于int类型最小值时,输出Integer.MIN_VALUE

  暂时只考虑了这么多种吧,代码如下:

 1 public int myAtoi(String str) {
 2     //对null和空串情况进行判断
 3     if(str == null || str.length() == 0){
 4         return 0 ;
 5     }
 6     //截除字符串的前面的空格
 7    char [] arr = str.trim().toCharArray() ;
 8    int temp ;    //乘子,表示正负
 9    int index ;   //表示最高位开始的index
10    //判断非空有效位的首位的情况
11    if((arr[0] == '-') && (arr.length > 1)){
12        temp = -1 ;
13        index = 1 ;
14    }else if((arr[0] <= '9') && (arr[0] >= '0')){
15        temp = 1 ;
16        index = 0 ;
17    }else if((arr[0] == '+') && (arr.length > 1)){
18        temp = 1 ;
19        index = 1 ;
20    }else{
21        return 0 ;
22    }
23    
24    long res = 0 ;
25    for(int i = index ; i < arr.length ; i++){
26        /*判断每一位是否是数字,不是则直接截断已经处理的结果
27         * 考虑到int类型的最长有效位数是10位,加上符号位11位,这里再附加一位保险位,
28         * 超过12位的肯定超出了有效范围我们不继续处理后面的,直接截断*/
29        if((arr[i] <= '9') && (arr[i] >= '0' && i < 13)){ 
30            res = res*10 + temp*(arr[i]-'0') ;
31        }else{
32            break ;
33        }
34    }
35    //判断输出的结果是否超出int类型的范围
36    if(res > Integer.MAX_VALUE ){
37        return Integer.MAX_VALUE ;
38    }else if(res < Integer.MIN_VALUE){
39         return Integer.MIN_VALUE ;
40     }else{
41         return (int)res ;            
42     } 
43 }