把字符串转换成整数

来源:互联网 发布:长鑫盛通软件 编辑:程序博客网 时间:2024/05/05 11:32

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


public class Solution {    public int StrToInt(String str) {        if(str == null || str.length() <= 0)            return 0;        int fuhao = 0;        char[] a = str.toCharArray();        if(a[0] == '-')            fuhao = 1;        int sum = 0;        for(int i = fuhao; i < a.length; i++)        {            if(a[i] == '+')                continue;            if(a[i] < '0' || a[i] > '9')                return 0;            sum = sum * 10 + a[i] - '0';        }        return fuhao == 0 ? sum : sum * -1;    }}
0 0
原创粉丝点击