题解 | #把字符串转换成整数(atoi)# 超易理解

把字符串转换成整数(atoi)

https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f

#include <climits>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    int StrToInt(string s) {
        // write code here
        int result = 0;
        bool isReachNum = false;	//判断是否开始转换了
        bool neg = false;			//判断正负
        for (auto ch : s) {
            if (ch == ' ' && !isReachNum)
			  	// 如果遇到空格,并且还没有开始转换就不管这个空格
                continue;
            if (ch == '-' && !isReachNum) {
			  	// 碰到负号,并且还没有开始转换,就当作负数了,并且现在就开始转换了。
                isReachNum = true;
                neg = true;
                continue;
            }
            if (ch == '+' && !isReachNum) {
			  	// 碰到正号并且还没有开始转换,就当作正数了,并且现在开始转换了。
                isReachNum = true;
                continue;
            }
            if (!(ch <= '9' && ch >= '0'))
			  	// 处理了正数和负数还有空格的场景,剩下碰到不是数字的直接retrun,空格的场景在最上面已经过滤了,剩下的只有是“空格+已经开始转换”。这个时候一定是异常了。
                return result * (neg ? -1 : 1);
            if (ch <= '9' && ch >= '0') {
			  //先设置为开始转换
                isReachNum = true;
                if (!isLargeThanMax(result, ch, neg))
				  	// 不是大数继续算
                    result = result * 10 + ch - '0';
                else
				  	// 大数直接溜
                    return neg ? INT_MIN : INT_MAX;
            }
        }
        return result * (neg ? -1 : 1);
    }

    bool isLargeThanMax(int result, char ch, bool neg) {
        if (result > INT_MAX / 10 || 
        (result == INT_MAX / 10 && ch - '0' > INT_MAX % 10)) {
		  	 // 1. 如果result > INT_MAX / 10 表示大数,因为它再乘以10,一定大于最大数。
		  	 // 2. 如果reulst == INT_MAX / 10时,只有当ch - '0' > INT_MAX % 10(也就是8)才表示大数。
            return true;
        }
        return false;
    }
};

全部评论

相关推荐

黑皮白袜臭脚体育生:春节刚过就开卷吗?哈基馆,你这家伙......
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务