题解 | #把字符串转换成整数#

把字符串转换成整数

http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e

public class Solution {
    public int StrToInt(String str) {
        //如果字符串为空,直接返回0
        if(str==null || str.length()==0){
            return 0;
        }
        int len=str.length();
        int status=1;//保留字符串的正负性
        int end=0;//截至位
        int res=0;//保存返回值
        if(str.charAt(0)=='+'){//若第一位为符号位,令截止位为1,且status=1
            end=1;
        }
        if(str.charAt(0)=='-'){
            status=-1;
            end=1;
        }
        for(int i=len-1,index=1;i>=end;i--,index*=10){//倒着遍历
            int temp=str.charAt(i)-'0';
            if(temp>=0 && temp<=9){//如果是数字则加入res
                res+=temp*index;
            }else{//不是数字直接结束,返回0
                return 0;
            }
        }
        return res*status;//成功转换为数字,乘上符号位。

    }
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务