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.
解题思路:
本题难度并不大,比较无聊,主要是要考虑到几个边界条件,本人也是提交数次才通过的。
JAVA代码如下:
static public int myAtoi(String str) {
if (str == null )
return 0;
str = str.trim();
if(str.length()==0)
return 0;
boolean isNagetive = false; if (str.charAt(0) == '-')
isNagetive = true;
long result = 0;
for (int i = 0; i < str.length(); i++) {
if(i==0&&(str.charAt(0)=='-'||str.charAt(0)=='+'))
continue;
int temp = str.charAt(i) - '0';
if (temp >= 0 && temp <= 9)
{
if(isNagetive){
result=result * 10 - temp;
}
else result = result * 10 + temp;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
} else break;
}
return (int) result;
}
C++
#include<algorithm>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
bool isFirstChar = true, isNagetive = false;
long result = ;
for (int i = ; i < str.length(); i++) {
if (isFirstChar&&str[i] == ' ')
continue;
if (isFirstChar&&str[i] == '-') {
isNagetive = true;
isFirstChar = false;
continue;
}
if (isFirstChar&&str[i] == '+') {
isFirstChar = false;
continue;
}
int temp = str[i] - '';
if (temp >= && temp <= )
{
if (isNagetive) {
result = result * - temp;
}
else result = result * + temp;
if (result > INT_MAX)
return INT_MAX; if (result < INT_MIN)
return INT_MIN;
}
else break;
isFirstChar = false;
}
return (int)result;
}
};