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

把字符串转换成整数

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;//成功转换为数字,乘上符号位。

    }
}
全部评论

相关推荐

05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务