题目:
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.
题目大概意思就是将随意输入的字符串转换成整型,难点是考虑所有的输入情况,换句话也可以说是, 主要是在题目理解上
所以,有必要解释一下题目的要求:
1. 首先需要丢弃字符串前面的空格;
2. 然后可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0。比如测试用例里就有个“+-2”),这道题还有个局限性,那就是在c++里面,+-1和-+1都是认可的,都是-1,而在此题里,则会返回0;
3. 字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回为“-123”;
4. 如果超出int的范围,返回边界值(2147483647或-2147483648)。
JAVA版本:
/*注意:此问题的目的是模糊指定(也就是说,没有给定的输入规格)。您负责收集前面的所有输入需求。**/
class Solution {
public int myAtoi(String str) {
if(str == null) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
int sign = 1;
int index = 0;
if (str.charAt(index) == '+') {
index++;
} else if (str.charAt(index) == '-') {
sign = -1;
index++;
}
long num = 0;
for (; index < str.length(); index++) {
if (str.charAt(index) < '0' || str.charAt(index) > '9')
break;
num = num * 10 + (str.charAt(index) - '0');
if (num > Integer.MAX_VALUE ) {
break;
}
}
if (num * sign >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (num * sign <= Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)num * sign;
}
}
C++版本:
int myAtoi(string str) {
long result = 0;
int indicator = 1;
for(int i = 0; i<str.size();)
{
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;
}
}
Python版本:
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
str = re.findall('(^[\+\-0]*\d+)\D*', str)
try:
result = int(''.join(str))
MAX_INT = 2147483647
MIN_INT = -2147483648
if result > MAX_INT > 0:
return MAX_INT
elif result < MIN_INT < 0:
return MIN_INT
else:
return result
except:
return 0
Python版本则主要是运用正则表达式