avatar
w*x
2
OVERFLOW的处理相当麻烦, 特别还要注意INT_MIN, INT_MAX的情况, 贴一个我修改了n
遍的代码:
int myatoi(const char* p)
{
assert(p);
//Judge signal
bool bNeg = false;
const char* pCur = p;
if(*pCur == '-' || *pCur == '+')
{
if (*pCur++ == '-')
bNeg = true;
}
//treat the rest as positive numeric number, so for negative number
//it is 2^31, and for positive number it is 2^31
unsigned int uLimit = bNeg ? 0x7FFFFFFF + 1 : 0x7FFFFFFF;
// The reson to use unsigned int rather than int is to deal with 2^31
unsigned int uRes = 0;
unsigned int uDummy = UINT_MAX/10; // used to judge overflow of unsigned
int
do
{
//Deals with illegal character
if (*pCur < '0' || *pCur > '9')
throw CException("Illegal character found");
//Get current digit
int nDigit = *pCur - '0';
//Detect the unsigned integer overflow
if (uRes > uDummy || (uRes == uDummy && nDigit > 6))
throw CException("Over flow detected");
//update uRes
uRes = uRes*10 + nDigit;
//Overflow situation if uRes isn't overflow
if (uRes > uLimit)
throw CException("Over flow detected");
pCur++;
}while (*pCur != 0); // WTF stupid error again, do while not while
return bNeg ? (int)(-uRes) : (int)(uRes);
}
avatar
s*m
3
所以我想用long存放中间结果以简化实现。
avatar
b*t
4
其实大家都太挑战自我
要我来implement 内部用long long 然后越界的话转成 INT_MIN INT_MAX
简单很多

n

【在 w****x 的大作中提到】
: OVERFLOW的处理相当麻烦, 特别还要注意INT_MIN, INT_MAX的情况, 贴一个我修改了n
: 遍的代码:
: int myatoi(const char* p)
: {
: assert(p);
: //Judge signal
: bool bNeg = false;
: const char* pCur = p;
: if(*pCur == '-' || *pCur == '+')
: {

avatar
s*n
5
要那么复杂么,只要判断前一个数和后一个数是否翻转了"-"即可
int atoi(char* str) {
bool neg = false;
if (*str=="-") {
str++;
neg = true;
} else if (*str=="+")
str++;
int value = 0;
while (*str) {
int digit = *str-'0';
if (digit>9 || digit<0) throw "error";
int newvalue = value*10 + neg?(-digit):digit;
if (value>0 && newvalue<0 || value<0 && newvalue>0) throw "overflow";
value = newvalue;
str++;
}
return value;
}
}
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。