博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode--String to Integer (atoi)
阅读量:6095 次
发布时间:2019-06-20

本文共 2091 字,大约阅读时间需要 6 分钟。

1.题目描述

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.
 
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
 
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
 
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
 
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

2.解法分析

只需注意几点即可:

  • 字符串之前的空格要去除,零串也要去除
  • 空串的状况
  • 正负号需要考虑
  • 溢出管理
  • 字符串之中出现异常字符的处理

对于以上几种情况,只有溢出管理比较麻烦,这里设置一个long long 类型的result,计算过程中一旦发现result超出INTMIN-INTMAX定义的int范围,直接返回,代码如下:

class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(str==NULL)return -1;
long long result=0;
int i=0;
bool isNegative=false;
bool isHeader=true;
while(str[i]!='\0')
{
if(isHeader)
{
if(str[i]==' '){i++;continue;}
if(str[i]=='-'){isNegative=true;i++;isHeader=false;continue;}
else
if(str[i]=='+'){isHeader=false;i++;continue;}
}
if(str[i]<'0'||str[i]>'9')break;
else
{
isHeader=false;
result=result*10+str[i]-'0';
if(-result
if(result>INT_MAX&&!isNegative)return INT_MAX;
}
i++;
}
 
if(isNegative)result*=-1;
return result;
}
};

转载于:https://www.cnblogs.com/obama/p/3270536.html

你可能感兴趣的文章
jq漂亮实用的select,select选中后,显示对应内容
查看>>
C 函数sscanf()的用法
查看>>
python模块之hashlib: md5和sha算法
查看>>
linux系统安装的引导镜像制作流程分享
查看>>
解决ros建***能登录不能访问内网远程桌面的问题
查看>>
pfsense锁住自己
查看>>
vsftpd 相关总结
查看>>
bash complete -C command
查看>>
解决zabbix 3.0中1151端口不能运行问题
查看>>
售前工程师的成长---一个老员工的经验之谈
查看>>
Get到的优秀博客网址
查看>>
压力测试对于BCH真的有意义吗?
查看>>
Node.js Web 模块
查看>>
Vlmcsd: 自建 KMS 激活服务器
查看>>
maven的私服搭建
查看>>
基于环状队列和迭代器实现分布式任务RR分配策略
查看>>
React Native Android 开发环境搭建,只需4步
查看>>
IntelliJ Idea编译报错:请使用 -source 7 或更高版本以启用 diamond 运算符
查看>>
YII中的$this->createUrl()参数前面斜杠使用说明
查看>>
java动态编译
查看>>