leetcode008:String to Integer (atoi)
来源:互联网 发布:视频后期调色软件 编辑:程序博客网 时间:2024/06/05 07:02
问题描述
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
问题分析
和leetcode007的题目用到的点基本相同,只是有些情况在运行测试后发现的,如“ +5df”这样的字符串是5,要考虑到,而不是返回错误,ok,直接上代码。
代码
class Solution {public: int atoi(string str) { int i = 0; while (i < str.length() && str[i] == ' ') { i++; } str = str.substr(i); if (str.length() <= 0) return 0; char arr[13];//选择13的目的是int型10进制最大值位数为10位,加上符号位为11位,防止溢出。 int flag = 0; for (i = 0; i < 12 && i < str.length(); i++) { if (i == 0 && (str[i] == '-' || str[i] == '+') || str[i] >= '0' && str[i] <= '9') arr[i] = str[i]; else break; } arr[i] = '\0'; int len = strlen(arr); if (!len || len == 1 && (arr[0] == '+' || arr[0] == '-')) return 0; long long k; sscanf(arr, "%lld", &k); if (k > INT_MAX) k = INT_MAX; if (k < INT_MIN) k = INT_MIN; return k; }};
0 0
- leetcode008:String to Integer (atoi)
- leetcode008 String to Integer (atoi)
- Leetcode008-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)
- 第一个awt程序
- [LeetCode]longest common/same prefix
- 第十八题
- 【简单常用】label
- Redis 服务监控
- leetcode008:String to Integer (atoi)
- hdu 1518 Square
- Web.xml配置详解
- ubuntu下ftp服务器搭建
- 第十九题
- Redis 服务管理
- UVA - 10313 Pay the Price
- 如何在linux下构建强大的build系统
- 第二十题