JZ49 把字符串转换成整数

把字符串转换成整数

https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&&tqId=11202&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

2021年9月17日00:08:11
2021年9月17日00:18:45

public class Solution {
    public int StrToInt(String str) {
        if(str.length()==0) return 0;
        boolean flag = false;
        if(str.charAt(0) == '+' ||  str.charAt(0) == '-'){
            if(str.charAt(0) == '-') flag= true;
            if(str.length()==1) return 0;
            str=str.substring(1,str.length());
        }     
        for(char c: str.toCharArray()){
            if(c>'9' || c<'0') return 0;
        }
        int res = 0;
        for(char c: str.toCharArray()){
            res = res*10 + c - '0';
        }
        return flag? -res:res;
    }
}
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
05-14 18:44
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务