把字符串转换成整数

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 

输入一个字符串,包括数字字母符号,可以为空,
如果是合法的数值表达则返回该数字,否则返回0
in:
+2147483647
    1a33
out:
2147483647
    0
public class Solution {
    public int StrToInt(String str) {
        if (str == null || str.equals("0") ||str.equals(""))
            return 0;
        boolean isPositive = true;
        if (str.charAt(0) == '+') {
            isPositive = true;
            str = str.substring(1);
        }
        else if (str.charAt(0) == '-') {
            isPositive = false;
            str = str.substring(1);
        }
        else {
            isPositive = true;
        }
         
        int ans = 0;
        int ary = 1;
        for (int i=str.length()-1; i>=0; i--) {
            if (!isDigit(str.charAt(i))) {
                return 0;
            }
            ans += ary * (str.charAt(i)-'0');
            ary *= 10;
        }
             
        ans = isPositive ? ans : -ans;
        return ans;
         
    }
     
    public boolean isDigit(char ch) {
        if (ch < '0' || ch > '9')
            return false;
        return true;
    }
}

 

posted @ 2016-09-02 11:31  Pickle  阅读(180)  评论(0编辑  收藏  举报