您的位置:首页 > 职场人生

网易面试题:写一段程序,实现atoi(const char* s)方法

2012-04-11 18:58 267 查看
描述:

  写一段程序,实现atoi(const char* s)方法。

示例代码:

#include <iostream>
using namespace std;
// 写一段程序,实现atoi(const char* s)方法。
// atoi用于将字符串转换成为整数。
// 比如 “123” => 123, “-246” => -246。

int Aatoi(const char *s)
{
// 主要的问题是负号的处理,不考虑其他字符的处理
int len = strlen(s);
if(0 == len) return -1;
bool is_plus = true;
if(s[0] != '-')
{
is_plus = true;
}
else
{
is_plus = false;
s++;
}
int result = 0;
while(*s!='\0')
{
result = result*10 + *s - '0';
s++;
}
if(is_plus == false)
return -result;
else
return result;
}

void main()
{
char s[] = "123";
cout << Aatoi(s) << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: