String to Integer (atoi)
来源:互联网 发布:语音播报软件 编辑:程序博客网 时间:2024/06/07 00:14
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 aconst char *
argument, please click the reload button to reset your code definition.
spoilers alert... click to show 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.
class Solution {public: int myAtoi(string str) { long result = 0; int indicator = 1; int n = str.size(); int pos = str.find_first_not_of(' '); if (str[pos] == '+' || str[pos] == '-') { indicator = str[pos] == '-'? -1 : 1; pos++; } while (pos < n && str[pos] >= '0' && str[pos] <= '9') { result = result*10 + str[pos] - '0'; if (indicator*result >= INT_MAX) { return INT_MAX; } if (indicator*result <= INT_MIN) { return INT_MIN; } pos++; } return result*indicator; }};
- 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)
- jQuery中$.fn的用法示例介绍
- 伪数组
- JavaScript数据类型
- 【编程经验】【编程习惯】虚类无法被实例化
- 易语言 小米注册机
- String to Integer (atoi)
- JPanel 的getGraphics
- pl sql 工具insert into 中文 后, select为乱码
- 黑马程序员----Java基础基础之IO流
- 变量、JAVA基本类型 、 运算符和表达式的学习
- LightOJ 1422 Halloween Costumes 【区间DP】
- Linux初探之如何查看帮助文档自学命令
- 关于sqlplus中出现"Connected to an idle instance"问题的处理
- 将bean对象写成xml格式