#include<iostream>
using namespace std;
int myatoi(const char*pstr)
{
int total = 0;
bool signal = false;
if (pstr == nullptr)
{
cout << "error" << endl;
return 0;
}
//跳过开头空格
while (*pstr==' ')
{
++pstr;
}
//判断是否带符号
if (*pstr == '-')
{
signal = true;
++pstr;
}
if(*pstr == '+')
++pstr;
while (*pstr)
{
if (*pstr >='0' && *pstr <= '9')
total = total*10 + *pstr - '0';//计算求值字符串的值
else if (*pstr != ' ') //在求值字符串内若出现非空格非数字字符则直接停止计算返回当前值
break;
++pstr;
}
if (signal)
total = -1 * total;
return total;
}
void reversestr(char* pstr)
{
if (pstr == nullptr)
return;
char* pBegin = pstr;
char* pEnd = pstr;
while (*pEnd)
{
++pEnd;
}
--pEnd;
while (pEnd > pBegin)
{
*pBegin = *pBegin ^ *pEnd;
*pEnd = *pBegin ^ *pEnd;
*pBegin = *pBegin ^ *pEnd;
++pBegin;
--pEnd;
}
}
const char* myitoa(int num)
{
static char res[16]{};
bool signal = false;
//先转正数处理
if (num < 0)
{
signal = true;
num = -num;
}
int i = 0;
while (num)//获得反序的字符串
{
res[i] = num % 10 + '0';
num = num / 10;
++i;
}
if (signal)//处理符号
{
int size = strlen(res);
res[size] = '-';
}
reversestr(res);//反转反序字符串得到正确字符串
return res;
}
int main()
{
cout << myatoi("123")<<endl;
cout << myatoi("-123") << endl;
cout << myatoi(" -124") << endl;
cout << myatoi(" - 125") << endl;
cout << myatoi("1 26") << endl;
cout << myatoi("- 1 27p") << endl;
cout << myatoi("- 1-28p") << endl;
cout << myatoi("12k7") << endl;
cout << myatoi(" -j27") << endl;
cout << myatoi(" j27") << endl;
cout << myatoi(" +27") << endl;
cout << myitoa(3200) << endl;
cout << myitoa(-3200) << endl;
return 0;
}
atoi函数与itoa函数的简单实现
最新推荐文章于 2023-11-22 09:11:31 发布