把字符串转化为整数 JAVA

public class Solution {
    public int StrToInt(String str) {
        if(str==null||str.length()==0){
            return 0;
        }
        int sum=0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (i == 0 && (c == '+' || c == '-'))
                continue;
            if (c < '0' || c > '9') 
                return 0;
            sum = sum * 10 + (c - '0');
        }
        if(str.charAt(0)=='-'){
            sum=-sum;
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42612582/article/details/121714746