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。
主要考虑的情况有以下几种:
暂时只考虑了这么多种吧,代码如下:
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 }