您的位置:首页 > 编程语言 > C语言/C++

Leetcode 8. String to Integer (atoi) (Easy) (cpp)

2016-07-13 11:34 429 查看
Leetcode 8. String to Integer (atoi) (Easy) (cpp)

Tag: Math, String

Difficulty: Easy

/*

8. String to Integer (atoi) (Easy)

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.

*/
class Solution {
public:
int myAtoi(string str) {
if (str.empty()) return 0;
long long num = 0;
int i = 0, sign = 1;
for (; str[i] == ' '; i++) {
}
if (str[i] == '-' || str[i] == '+') sign = 1 - 2 * (str[i++] == '-');
for(int j = i; j < str.length(); j++) {
if(str[j] >= '0' && str[j] <= '9') {
num = num * 10 + (str[j]-'0');
if(num > INT_MAX) return sign > 0 ? INT_MAX : INT_MIN;
}
else break;
}
return (int)num * sign;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: