String to Integer (atoi)
来源:互联网 发布:drgs病案编码软件 编辑:程序博客网 时间:2024/04/25 18:22
题目:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
例子:
input "+1" output 1
input "1a" output 1
input "a1" output 0
input "+23a1" output 23
input "112 22" output 112
input " - 21" output 0
最大最小值:INT_MAX (2147483647) or INT_MIN (-2147483648)
代码如下:
int atoi(const char *str) {
if(str==NULL)return 0;
long long result=0;
while(*str==' ')str++;
bool flagsymbol=true,flagfirst=true,flagnum=true,flagflag=true;
int n=0;
while(*str!='\0')
{
if(*str=='-'||*str=='+')
{
n++;
flagnum=false;
if(n>1)return 0;
if(*str=='-')flagsymbol=false;
}
else if(*str>='0'&&*str<='9')
{
if(flagnum||flagflag)
result=result*10+(*str-'0'),flagnum=false;
}
else
{
if(flagfirst)return 0;
flagflag=false;
}
str++;
flagfirst=false;
}
if(flagsymbol)
{
if(result>INT_MAX )return INT_MAX ;
return result;
}
else
{
if(result>2147483648)return INT_MIN ;
result*=-1;
return result;
}
}
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer(atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- 解决Ubuntu下Swing图形界面的乱码问题
- sublimetext2的配置文件Preferences.sublme-settings文件
- hdu-1518-Square
- Validate FQDN of SQL Server Computer failed
- SQL Server 事务执行一半出错是否自动回滚整个事务
- String to Integer (atoi)
- ubuntu与windows文件共享
- Android系统介绍及平台特性
- CreateMutex和WaitForSingleObject组合的有关问题
- Ajax+Ashx 无刷新分页
- BSOD分析之空指针引用
- Android 设置字体
- libSvm与matlab问题处理
- 解决开发android应用时虚拟机启动、运行较慢的问题