字符串转整数的java实现

来源:互联网 发布:滴胶手机壳 知乎 编辑:程序博客网 时间:2024/05/16 06:12

问题:

把一个字符串转成一个整数。

思路:

其实,这道题考的不是怎么去把一个数转成一个整数,而是考你是否能够把所有的情况都考虑完全,我们应该考虑的因素如下:

1. 这个字符串是否是空的。

2. 这个字符串是否有非法字符(非0-9之间的字符)。

3.这个数是正数或者是负数的情况(第一个字符是否为+,-)。

4. 是否存在溢出的情况(这个比较难考虑到)。

[java] view plaincopy
  1. public static long atoi(String str) throws Exception {  
  2.       
  3.     boolean negative = false;  
  4.     long value = 0;  
  5.       
  6.     if (str == null || str.equals("")) {  
  7.         throw new Exception("null string or the string has no character!");  
  8.     }   
  9.       
  10.     for (int i = 0; i < str.length(); i++) {  
  11.         if (i == 0 && (str.charAt(0) == '-' || str.charAt(0) == '+')) {  
  12.             if (str.charAt(0) == '-') {  
  13.                 negative = true;                  
  14.             }  
  15.         } else {  
  16.             if (str.charAt(i) >= '0' && '9' >= str.charAt(i)) {  
  17.                 value = value * 10 + (str.charAt(i) - '0');  
  18.                 if (value > Integer.MAX_VALUE) {  
  19.                     throw new Exception("OUT OF INTEGER RANGE");  
  20.                 }  
  21.             } else {  
  22.                 throw new NumberFormatException("not an integer");  
  23.             }  
  24.         }  
  25.     }  
  26.     return negative == true ? value * -1 : value;             
  27. }  

转载请注明出处: http://blog.csdn.net/beiyeqingteng
0 0
原创粉丝点击