g***j 发帖数: 1275 | 1 我看到网上有很多code其中处理overflow是这么做的,这对么?如果overflow的话,怎
么可以和INT_MAX比较呢?
这个overflow的result已经是负数了啊
while(*str){
if(isdigit(*str)){
result=result*10+*str-'0';
if(sign&&result>INT_MAX) return INT_MAX;
else if(!sign&&-result
str++;
}
else break;
} |
s***5 发帖数: 2136 | |
g***j 发帖数: 1275 | 3 我这样写的,可以么?
虽然大小集合都过了,但是,感觉还是有一个bug,因为直接求abs(INT_MIN) 会
overflow,所以,我直接用INT_MAX来代替了。
只贴了中间的while循环
while(*index >= '0' && *index <= '9') {
int val = *index -'0';
int temp = result;
for(int i = 0; i < 9; i++) {
if(sign > 0) {
if(INT_MAX - temp > result) temp += result;
else return INT_MAX;
} else {
if(INT_MAX - temp > result) temp += result;
else return INT_MIN;
}
}
if(sign > 0 && INT_MAX - temp< val ) return INT_MAX;
if(sign < 0 && INT_MAX - temp< val) return INT_MIN;
temp += val;
result = temp;
index++;
}
【在 s***5 的大作中提到】 : 答案肯定错的 : 乘之前就要检查overflow
|
g***j 发帖数: 1275 | 4 为啥这个代码大小集合都可以过呢? 明明有result*10啊
class Solution {
public:
int atoi(const char *str) {
long long result(0);
bool sign(true);
for(;*str && *str==' ';++str);
if(*str=='-'){
sign=false;
++str;
}
else if(*str=='+') ++str;
while(*str){
if(isdigit(*str)){
result=result*10+*str-'0';
if(sign&&result>INT_MAX) return INT_MAX;
else if(!sign&&-result
str++;
}
else break;
}
if(sign) return result;
else return -result;
}
};
【在 s***5 的大作中提到】 : 答案肯定错的 : 乘之前就要检查overflow
|
s***5 发帖数: 2136 | 5 INT_MAX应该是基于32为整形数的,~2billion,long long在大于INT_MAX的时候还不
会overflow
【在 g***j 的大作中提到】 : 为啥这个代码大小集合都可以过呢? 明明有result*10啊 : class Solution { : public: : int atoi(const char *str) { : long long result(0); : bool sign(true); : for(;*str && *str==' ';++str); : if(*str=='-'){ : sign=false; : ++str;
|
r*********n 发帖数: 4553 | 6 要考虑overflow,为什么不从低位加到高位呢?
假如当前位的值是cur,判断一下之前位总和val是不是满足
val <= numeric_limits::max() - cur
如果满足,则val += cur and recurse,否则throw overflow_error。这里有一个问题
是连续很多零,直接导致遇到非零位计算cur的时候,cur直接overflow,但这个问题很
好解决,只要track连续零的个数即可。 |
s*******u 发帖数: 220 | 7 你再仔细看看代码,result肯定是定义成long的;返回的时候cast成int
【在 g***j 的大作中提到】 : 我看到网上有很多code其中处理overflow是这么做的,这对么?如果overflow的话,怎 : 么可以和INT_MAX比较呢? : 这个overflow的result已经是负数了啊 : while(*str){ : if(isdigit(*str)){ : result=result*10+*str-'0'; : if(sign&&result>INT_MAX) return INT_MAX; : else if(!sign&&-result: str++; : }
|