g*********s 发帖数: 1782 | 1 this is my solution casting an unsigned int to an int. but gcc gives me
warning:
string_api.cpp: In function ‘bool overflow(unsigned int, bool, char)’:
string_api.cpp:330: warning: integer overflow in expression
string_api.cpp: In function ‘int str2int(const char*)’:
string_api.cpp:346: warning: integer overflow in expression
explict type casting can fix the warning. but i don't like this solution
very much. anyone has a better alternative?
static
bool overflow(unsigned int val, bool negative, c... 阅读全帖 |
|
C***y 发帖数: 2546 | 2 我的想法是
先转成一个long,然后和INT_MIN和INT_MAX比
最后convert成int输出
不知这个办法是否合适 |
|
j*****u 发帖数: 1133 | 3 在每次
result = result * 10 + str[i] - '0';
之后check result < 0,如果overflow就会变负
如果C#的话用checked{ } wrap,或者complier打开/checked+,就会自动throw Ov
erflowException() |
|
|
l*****a 发帖数: 14598 | 5 之前处理也可以,也许更直接
目标 result*10+str[i]-'0'<=MAX_INT
1) result
2) result=MAX_INT/10 && str[i]-'0'<=MAX_INT/10 |
|
C***y 发帖数: 2546 | 6 是不是应该先判断一下 result==INT_MIN
result==INT_MIN的时候虽然<0,但实际上是没有overflow的 |
|
m******m 发帖数: 19 | 7
str[i]-'0'<=MAX_INT%10 ? |
|
l*****a 发帖数: 14598 | 8 什么问题?
think about last digit of 65534 , 65535 and 65538 |
|
m******m 发帖数: 19 | 9
我的意思是:不是 str[i]-'0'<=MAX_INT/10,应该是str[i]-'0'<=MAX_INT%10吧 |
|
|
|
g*********s 发帖数: 1782 | 12 发信人: lolhaha (haha), 信区: JobHunting
标 题: Re: str2int中overflow该如何处理?
发信站: BBS 未名空间站 (Sun Feb 20 18:18:40 2011, 美东)
之前处理也可以,也许更直接
目标 result*10+str[i]-'0'<=MAX_INT
1) result
2) result=MAX_INT/10 && str[i]-'0'<=MAX_INT/10
but notice the negative bound is different from the positive bound. that's
why i say it's tricky. |
|
g*********8 发帖数: 64 | 13 int str2int(string s){
assert(s.length()>0);
bool isNeg=false;
unsigned int num=0,i=0,d=0;
if(s[0]=='-'){
isNeg=true;
i=1;
}
while(i
d=s[i]-'0';
num=num*10+d;
assert(d>=0&&d<=9);
assert(num<=INT_MAX);
i++;
}
if(isNeg) num=-1*num;
return num;
}
我写的代码,望指正,处理了溢出,负数,非数值,还有什么异常没有处理? |
|