博文中会简要介绍Leetcode P0008题目分析及解题思路。
“String to Integer (atoi)”是一道比较简单的纯数学问题,主要考察边界条件的判断,如果是边界最值的十分之一,则直接返回边界最值,题干如下:
Implement atoi which converts a string to an integer.
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.
Note:
Only the space character ‘ ‘ is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 − 1) or INT_MIN (−2^31) is returned.
以下是Java的题解代码实现。
class Solution {
public int myAtoi(String str) {
int res = 0;
if (str.trim().length() == 0)
return 0;
char[] ch = str.trim().toCharArray();
if(ch.length == 1 && (ch[0] == '+' || ch[0] == '-'))
return 0;
if(ch[0] == '+' || ch[0] == '-' || (ch[0] >= '0' && ch[0] <= '9')){
if(ch[0] >= '0')
res = ch[0] - '0';
int idx = 1;
while(idx < ch.length){
if(ch[idx] >= '0' && ch[idx] <= '9'){
if((res * 10L + (ch[idx] - '0')) > Integer.MAX_VALUE){
return (ch[0] == '-') ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
res = res * 10 + (ch[idx] - '0');
++idx;
}
else
break;
}
}
return (ch[0] == '-') ? 0 - res : res;
}
}
以下是C++的题解代码实现。
class Solution {
public:
int myAtoi(string str) {
if (str.empty())
return 0;
str = str.erase(0, str.find_first_not_of(" "));
if (str.empty())
return 0;
if (str.length()==1 && (str[0] == '-' || str[0] == '+'))
return 0;
int integer = 0;
string temp("");
if (str[0] == '+' || str[0] == '-')
temp = str.substr(1);
else
temp = str;
if (temp[0] >= '0' && temp[0] <= '9') {
for (auto idx=0; (idx<temp.length() && (temp[idx] >= '0' && temp[idx] <= '9')); ++idx) {
if (integer*10L+(temp[idx]-'0')*1L > INT_MAX || integer*10L+(temp[idx]-'0')*1L < INT_MIN) {
return ((str[0] == '-')? INT_MIN: INT_MAX);
}
integer = integer*10+(temp[idx]-'0');
}
}
return ((str[0] == '-')? -integer: integer);
}
};