第十八周(String to Integer (atoi))
目录:
- 本周完成题目
- 主要过程思路
- 相关代码
一、本周完成题目
本周共完成1道题目,1道Medium。
具体完成题目及难度如下表:
# | Title | Difficulty |
---|---|---|
8 | String to Integer (atoi) | Medium |
题目内容
1、String to Integer (atoi)
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.
题目大意:给定一个字符串,将其转化为整形数字。(注意:需要考虑越界情况,大于边界值IN_MAX或小于IN_MIN需要返回边界值。另外字符串中数字以外的部分不用考虑)
二、主要过程思路
1、String to Integer (atoi):
本题比较简单,核心是读取每个数字然后加入到已读入的数字中。同时已读入的数字乘十。
另外,需要考虑前面的“-”和“+”,如果有的话改变indicator,表示数字是正的或负的。如果发现result的值大于边界值INT_MAX或者小于INT_MIN的时候,返回边界值,停止下面的访问。
三、相关代码
String to Integer (atoi)
class Solution {
public:
int myAtoi(string str) {
long result = 0;
int indicator = 1;
int i=0;
i = str.find_first_not_of(' ');
if(str[i] == '-' || str[i] == '+')
indicator = (str[i++] == '-')? -1 : 1;
while('0'<= str[i] && str[i] <= '9') {
result = result*10 + (str[i++]-'0');
if(result*indicator >= INT_MAX) return INT_MAX;
if(result*indicator <= INT_MIN) return INT_MIN;
}
return result*indicator;
}
};