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

把字符串转换成整数

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

public class Solution {
    public int StrToInt(String str) {
        int ret = 0;
        int flag = 1;
        String num = "0123456789";
        if(str.isEmpty()) {
            return 0;
        }
        char ch = str.charAt(0);
        if (ch == '+') {
            flag = 1;
        }else if(ch == '-') {
            flag *= -1;
        }else {
            if(num.contains(ch+"")) {
                ret = str.charAt(0)-'0';
            }
        }
        for(int i = 1; i < str.length(); i++) {
            ch = str.charAt(i);
            if(!num.contains(ch+"")) {
                return 0;
            }
            ret = ret*10 + ch-'0';
        }
        return flag*ret;
    }
}

全部评论

相关推荐

12-27 22:14
门头沟学院 Java
点赞 评论 收藏
分享
12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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