week5-leetcode #8-String to Integer (atoi)[Medium]
题目链接:https://leetcode.com/problems/string-to-integer-atoi
Question
Implement atoi to convert a string to an integer.
Solution
time complecity: O(n)
space complecity: O(n)
runtime:12ms
class Solution {
public:
int myAtoi(string str) {
int length = str.length();
bool spaceFlag = false;
int notSpacePos = 0;
int numberPos = 0;
bool hasNumber = false;
for (int i = 0; i < length; i++) {
// 空格字符
if (isspace(str[i])) {
continue;
} else {
if (spaceFlag == false) {
notSpacePos = i;
spaceFlag = true;
}
// 不是数字
if (!isdigit(str[i]) && str[i] != '+' && str[i] != '-') {
return 0;
} else {
if (isdigit(str[i])) {
numberPos = i;
} else {
// +/-后面需要跟数字
if (!isdigit(str[i+1])) {
return 0;
} else {
numberPos = i+1;
}
}
hasNumber = true;
break;
}
}
}
// 记录数字
vector<int> numberVec;
// 有数字
if (hasNumber) {
for (int i = numberPos; i < length; i++) {
if (isdigit(str[i])) {
numberVec.push_back(str[i]-'0');
} else {
break;
}
}
int returnNumber = 0;
int numberLength = numberVec.size();
cout << "numberLength: " << numberLength << endl;
for (int i = 0; i < numberLength; i++) {
returnNumber += numberVec[numberLength-i-1]*pow(10, i);
}
// 判断负数
if (str[numberPos-1] == '-') {
returnNumber = -1*returnNumber;
}
if (returnNumber == INT_MIN) {
if (str[numberPos-1] == '-')
returnNumber = INT_MIN;
else
returnNumber = INT_MAX;
}
return returnNumber;
} else {
return 0;
}
}
};
思路:本题解题关键在于充分了解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.
需要注意
- 当数字足够大或者足够小的时候返回一个INT的最大值或者最小值
- 注意数字前面可能存在正负号,需要稍微考虑一下