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

把字符串转换成整数

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

import java.util.*;
public class Solution {
    public int StrToInt(String str) {
        char[] ch = str.toCharArray();
        if(ch == null || ch.length == 0) {
            return 0;
        }
        int flg = 1;
        if(ch[0] == '+') {
            ch[0] = '0';
        } 
        if(ch[0] == '-') {
            flg = -1;
            ch[0] = '0';
        }
        int sum = 0;
        for(int i = 0; i < ch.length; i++) {
            if(ch[i] < '0' || ch[i] > '9') {
                return 0;
            }
            sum = sum * 10 + ch[i] - '0';
        }
        return flg * sum;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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