Leetcode_String to Integer (atoi)
来源:互联网 发布:cydia网络错误 编辑:程序博客网 时间:2024/06/05 02:56
主要注意分析几种特殊的输入:
1 不规则的输入,但是有效:"-3924x8fc","+432"
2 无效格式,"++c","++1"
3 数据溢出
其中数据溢出的判断:
To deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.
就是判断当前的数据时候已经大于INT_MAX的十分之一,是则溢出;或者,当前数据等于INT_MAX的十分之一,则需要判断此时再加进去的字符数据是否大于INT_MAX的最后一位。
class Solution {public: int atoi(const char *str) {const int n=strlen(str);int i=0;int sign=1;while(str[i]==' '&&i<n)++i;if(str[i]=='+'){++i;}else if(str[i]=='-'){sign=-1;++i;}int num=0;for(;i<n;++i){if(str[i]<'0'||str[i]>'9')break;if(num>INT_MAX||(num==INT_MAX/10&&(str[i]-'0')>INT_MAX%10))//判断是否会产生溢出{return sign==1?INT_MAX:INT_MIN;}num=num*10+str[i]-'0';}return num*sign; }};方法二:直接用streamstring即可转换数据类型
class Solution {public: int atoi(const char *str) {stringstream stream;stream<<str;int num;stream>>num;return num; }};
0 0
- Leetcode_String to Integer (atoi)
- LeetCode_String to Integer (atoi)
- ***(leetcode_string) String to Integer (atoi)
- Leetcode_string-to-integer-atoi(c++ version)
- Leetcode_String To Integer
- 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)
- C专家编程 读书笔记1
- 并发框架LMAX Disruptor资料总汇
- ECIF和CRM区别 (转)
- unity 脚本 function 生命周期 MonoBehaviour Mono行为
- Problem 039——UVa 442 - Matrix Chain Multiplication
- Leetcode_String to Integer (atoi)
- [算法导论·ISAP]网络流学习笔记
- 等待队列wait_queue_head_t使用
- cocos2d js 3.2 技能冷却按钮的简单实现
- 115 藥圃 鄭琢
- 如何用EA生成代码并将生成的代码放在VS搭建好的框架中
- 图片滑动组件iSlider
- Sync Object in OpenGL (about GPU Fence)
- 在Windows 7上搭建 Ruby环境