【剑指offer】把字符串转换成整数(溢出判断)
把字符串转换成整数
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
class Solution { public: int StrToInt(string str) { //关键是判断整数的上下界溢出,利用INT_MIN INT_MAX int n = str.size(), s = 1; long long res = 0; if(!n) return 0; if(str[0] == '-') s = -1; for(int i = (str[0] == '-' || str[0] == '+') ? 1 : 0; i < n; ++i){ if(!('0' <= str[i] && str[i] <= '9')) return 0; if(s == 1 && (res > INT_MAX / 10 || res == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)){ res = 0; break; } if(s == -1 && (res < INT_MIN / 10 || res == INT_MIN / 10 && (str[i] - '0') > -(INT_MIN % 10))){ res = 0; break; }//边界条件值得记住 res = (res << 1) + (res << 3) + s*(str[i] & 0xf);//res=res*10+str[i]-'0'; } return res; } };