问题:

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

思路:

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

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

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

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

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

public class StringReverse {
    public static long atoi(String str) throws Exception {
        long value = 0;
        boolean negative = false;
        if(str == null || "".equals(str) ){
            throw new Exception("the str cannot be null!");
        }
        for(int i = 0; i<str.length() ; i++) {
            if(i==0 && (str.charAt(0)=='+' || str.charAt(0)=='-') ) {
                if(str.charAt(0)=='-') {
                    negative = true;
                }
            }else {
                if(str.charAt(i)>='0' && str.charAt(i)<='9') {
                    value = value*10 + str.charAt(i)-'0';
                    if (value > Integer.MAX_VALUE) {  
                        throw new Exception("OUT OF INTEGER RANGE");  
                    } 
                }else {
                    throw new NumberFormatException("not an integer!");
                }
            }
        }
        
        return negative==true ? -1*value:value;
    }
    
    public static void main(String[] args) {
        try {
            System.out.println(atoi("-9857"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

以上实现和思路 转自http://blog.csdn.net/beiyeqingteng/article/details/7000034 


 

以下是自己的进一步思考:

如果用第一段代码的做法,对于一个n位的数(不考虑第一位是符号的情况),第n位要乘以(n-1)次的10,以此类推,这样会乘以许多次10,影响效率。

有人提到,可以用一个数组事先存好10000,1000,100,10,1这样的数,按位对应乘。其实可以不用数组,对于这个n位数字,可以直接每一位乘以10^(n-1)

减少乘法运算次数:

    public static long atoi(String str) throws Exception {
        long value = 0;
        boolean negative = false;
        if(str == null || "".equals(str) ){
            throw new Exception("the str cannot be null!");
        }
        int num_lengths = str.length();
        if(str.charAt(0)=='+' || str.charAt(0)=='-') {
            if(str.charAt(0)=='-') {
                    negative = true;
                    num_lengths--;
             }
        }
        
        for(int i=(str.length() - num_lengths); i<str.length();i++ ,num_lengths--) {
             if(str.charAt(i)>='0' && str.charAt(i)<='9') {
                 System.out.println(str.charAt(i)-'0');
                 value +=  (str.charAt(i)-'0')*Math.pow(10, (num_lengths-1));
                  if (value > Integer.MAX_VALUE) {  
                      throw new Exception("OUT OF INTEGER RANGE");  
                  } 
              }else {
                  throw new NumberFormatException("not an integer!");
              }
        }
        return negative==true ? -1*value:value;
    }

 

 

posted on 2013-11-19 12:36  SwitchBlade  阅读(1692)  评论(0编辑  收藏  举报