8、int atoi(const char*pstr)関数の機能を直接実現できるコードを作成してください
1682 ワード
/************************************************************************/
/* 8、 int atoi(const char * pstr) */
/************************************************************************/
// ,
bool isToIntValid =true;
int strToInt(const char *str)
{
long long num = 0;
int mark = (*str== '-' ? -1: 1);
long long upperBound = numeric_limits::max();;
if(mark == -1)
++upperBound;
const char* temp = (*str == '+' || *str == '-') ? str + 1: str;
for( ;*temp >= '0' && *temp <= '9'; ++temp)
{
num = num * 10 + *temp - '0';
if(num > upperBound)
{
// ,atoi
isToIntValid = false;
num = upperBound;
break;
}
}
if(*temp !='\0' || *str == '0')
isToIntValid = false;
return static_cast(mark * num);
}
void testOfstrToInt()
{
assert(atoi("+1234") == strToInt("+1234"));
assert(atoi("-1234") == strToInt("-1234"));
assert(atoi("+aaa234") == strToInt("+aaa234"));
assert(atoi("aaa1234") == strToInt("aaa1234"));
assert(atoi("-1234a") == strToInt("-1234a"));
assert(atoi("1234") == strToInt("1234"));
assert(atoi("12a34") == strToInt("12a34"));
assert(atoi("aaaa") == strToInt("aaaa"));
assert(atoi("0123") == strToInt("0123"));
//
assert(atoi("123456789012345123456") == strToInt("123456789012345123456"));
assert(atoi("-123456789012345123456") == strToInt("-123456789012345123456"));
}