由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 关于atoi的overflow
相关主题
问一个atoi overflow的问题atoi很不好写,头都大了...
经典题atoi的溢出处理str2int中overflow该如何处理?
函数atoi的实现大牛,过来讨论一下这道题
reverse an integer 怎么判断是否 overflow 来着请问如何安全地reverse 一个integer
帮忙看看我写的atoi有没有bug, 谢谢问个越界的问题
onsite完,攒rp系列(二)请问,string to long
atoi overflow怎么办?找最大俩数的代码怎么写?
写了个atoi,大家帮看有没有哪里错了?atoi的溢出处理的想法
相关话题的讨论汇总
话题: int话题: pos话题: ans话题: max话题: max1
进入JobHunting版参与讨论
1 (共1页)
o****d
发帖数: 2835
1
http://discuss.leetcode.com/questions/192/string-to-integer-ato
Am I right?
We can separate INT_MAX and INT_MIN to first n-1 digits and last one digit,
which can be used to check overflow before the answer really overflows. Note
that abs(INT_MIN)=INT_MAX+1.
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int pos=0;
//skip whitespace
while(str[pos]==' ')pos++;
//check if negative
int negative=0;
if(str[pos]=='-')
{
negative=1;
pos++;
}
else if(str[pos]=='+')
pos++;
if(str[pos]=='\0') return 0;
//separate INT_MAX to first n-1 digits and the last one digit
//INT_MIN as well
//NOTE that abs(INT_MIN) = INT_MAX + 1
int max1, max2, min1, min2;
max1=INT_MAX/10;
max2=INT_MAX-max1*10;
if(max2+1==10)
{
min1=max1+1;
min2=0;
}
else
{
min1=max1;
min2=max2+1;
}
int ans=0;
while(isdigit(str[pos]))
{
//check if overflow
if(!negative)
{
if(ans>max1 || ans==max1&&(str[pos]-'0')>=max2)
return INT_MAX;
}
else
{
if(ans>min1 || ans==min1&&(str[pos]-'0')>=min2)
return INT_MIN;
}
ans = ans*10+(str[pos]-'0');
pos++;
}
if(negative) ans=-ans;
return ans;
}
int isdigit(char c)
{
if(c>='0' && c<='9')
return 1;
else
return 0;
}
};
1 (共1页)
进入JobHunting版参与讨论
相关主题
atoi的溢出处理的想法帮忙看看我写的atoi有没有bug, 谢谢
问两道bloomberg的题目onsite完,攒rp系列(二)
ms面试问了atoi,结果搞了半天我还是搞错了atoi overflow怎么办?
amazon一面面经写了个atoi,大家帮看有没有哪里错了?
问一个atoi overflow的问题atoi很不好写,头都大了...
经典题atoi的溢出处理str2int中overflow该如何处理?
函数atoi的实现大牛,过来讨论一下这道题
reverse an integer 怎么判断是否 overflow 来着请问如何安全地reverse 一个integer
相关话题的讨论汇总
话题: int话题: pos话题: ans话题: max话题: max1