字符串转整数

public class Solution {
    public int StrToInt(String str) {
        
        if (str == null || str.trim().length() < 1) {
            return 0;
        }
        char op = str.charAt(0);
        int start = 0;
        int flag = 0;
        if (op == '+') {
            start++;
            flag = 1;
        } else if (op == '-') {
            start++;
            flag = -1;
        }
        long num = 0;
        for (int i = start; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {
                int temp = Character.getNumericValue(str.charAt(i));
                num = num * 10 + temp;
            } else {
                return 0;
            }
        }
        return (int) (flag >= 0 ? num == ((int) num) ? num : 0 : -num == ((int) -num) ? -num : 0);
    }
}

 

posted @ 2019-12-10 12:30  java渣渣  阅读(189)  评论(0编辑  收藏  举报