8. String to Integer (atoi)

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.

---

1. 不规则输入,但是有效
"-3924x8fc",-3924

"  +  413", 413

2. 无效格式
 " ++c", " ++1"
3. 溢出数据
"2147483648"

---

public int atoi(String str) {

        str = str.trim();
        boolean sign = true;
        long rst = 0;

        // check length
        if (str.length() == 0)
            return 0;

        // sign
        if (str.charAt(0) == '-')
            sign = false;

        for (int i = 0; i < str.length(); i++) {
            int val = str.charAt(i) - '0';
            if (val >= 0 && val <= 9) {
                rst = rst * 10 + val;
            } else {
                if (i > 0)
                    break;
            }

        }

        if (!sign)
            rst = -rst;

        if (rst > Integer.MAX_VALUE)
            rst = Integer.MAX_VALUE;

        if (rst < Integer.MIN_VALUE)
            rst = Integer.MIN_VALUE;

        return (int) rst;
    }

 

posted @ 2013-08-30 00:09  LEDYC  阅读(224)  评论(0)    收藏  举报