如题,itoa 不仅能把字符串转换成整型,还可以自选进制然后转换过去,实在太方便了,有什么可以替代吗?
自己写实现 给你个例子奥atoi
class Solution {
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
public:
// 是空格符
bool isspace(char c)
{
return c == ' ' || c == '\r' || c == '\n' || c == '\t' || c == '\f' || c == '\b';
}
// 是数字
bool isdigit(char c)
{
return c >= '0' && c <= '9';
}
// 字符串转int数字
int intatoi(string s)
{
int max[10] = {2,1,4,7,4,8,3,6,4,7};
bool isoverflow = false;
int result = 0;
int count = 0;
char sign = '+';
while (isspace(s[count]))
{
count++;
}
if (s[count] == '-' || s[count] == '+')
{
sign = s[count];
count++;
}
while(s[count] == '0')
{
count++;
}
int temp = count;
int num = 0;
while(isdigit(s[temp++]))
{
num++;
}
if (num == 10)
{
if (sign == '-')
{
max[9]++;
}
for (int i = 0; i < 10; i++)
{
if (s[count + i] - '0' > max[i])
{
result = INT_MAX;
isoverflow = true;
break;
if (sign == '-')
{
result = -result - 1;
}
}
else if (s[count + i] - '0' < max[i])
{
isoverflow = false;
break;
}
}
}
if (num < 11 && !isoverflow)
{
while(isdigit(s[count]))
{
if (result == 214748364 && s[count] - '0' > 7 && sign == '-')
{
return INT_MIN;
}
result = result * 10 + (s[count++] - '0');
}
if (sign == '-')
{
result = -result;
}
}
else
{
result = INT_MAX;
if (sign == '-')
{
result = -result - 1;
}
}
return result;
}
int myAtoi(string s) {
int result = intatoi(s);
return result;
}
};