水题

https://leetcode.com/problems/string-to-integer-atoi/

水题,把String 转换为 int 并 ,考虑各种情况 , 各种提交 ,看不通过的测试, 感觉自己严谨度严重不足啊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
    public int myAtoi(String str) {
        int index =0 ;//当前遍历的位置
        str = str.trim() ;//去掉空字符
        int len = str.length() ;
        if(len==0) return 0 ;
        boolean flag = true ;   //正负的标识
        char c  = str.charAt(0);
        if(c=='-'||c=='+'){    //判断符号, 记录 flag
            index++ ;      //有符号就遍历下一个字符
            if(c=='-') flag=false ;    
        }      
        long number =0;    //因为有可能会在运算时溢出 ,用long 保存转换结果到 number 中
        while(index< len){
            char ch = str.charAt(index) ;
            if(ch<='9' && ch>='0'){
              number = number * 10 + (ch - '0') ;//计算当前转换成的int
            }
            else break ;
                     
            if(flag)//得出当前结果后, 判断是否有溢出, 如果溢出,按照题目要求 存值到number中
            {
                if(number> Integer.MAX_VALUE){
                    number=Integer.MAX_VALUE ;
                    break ;
                }
            }else{
                if(-number< Integer.MIN_VALUE){
                    number=Integer.MIN_VALUE ;
                    break ;
                }
            }<br>                        index++;//没有溢出就 到下一个字符中
        }              
        if(flag) return (int) number;
        else return -(int)number ;
    }
}

  有趣的是, 当输入的是 负溢出时,number是 -2147483648 , 由于补码 的关系, return -(int)number  得到的值 仍然 是 -2147483648 哦.

posted @   javacoderbill  阅读(123)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示