剑指offer 把字符串转换为整数

题目描述:

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

解题思路:

首先字符串第一位是符号位,提前解析,其次如果字符串中含有非0-9字符则返回0,同时字符串长度为0,返回0。

代码(java):

public class Solution {
    public int StrToInt(String str) {
        int index=0;
        if(str.length()==0)return 0;
        boolean neg=false;
        if(str.charAt(0)=='-'){
            index=1;
            neg=true;
        }
        else if(str.charAt(0)=='+'){
            index=1;
        }
        int sum=0;
        for(;index<str.length();index++){
            if(str.charAt(index)>'9' || str.charAt(index)<'0')return 0;
            sum=sum*10+(int)(str.charAt(index)-'0');
        }
        return neg ? 0-sum : sum ;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/88689621