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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
题意不说了,思想也很简单,但是要注意处理各种可能出现的exception,这道题考察的主要就是对各种exception的判断和处理。
代码如下:
import java.util.ArrayList;
public class Solution
{
public int myAtoi(String str)
{
if (str == null || str.length() < 1)
return 0;
// trim white spaces
str = str.trim();
boolean flag = true;
// check negative or positive
int i = 0;
if (str.charAt(0) == '-')
{
flag = false;
i++;
} else if (str.charAt(0) == '+')
{
flag=true;
i++;
}
// use double to store result
double result = 0;
// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9')
{
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == false)
result = -result;
// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}
public static void main(String[] args)
{
Solution solution=new Solution();
System.out.println(solution.myAtoi("2147483648"));
}
}
C++做法如下:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
/*
下面的做法是做不到AC的,但是可以处理各种情况
这道题最麻烦的就是各种乱七八糟的输入字符串
*/
class Solution
{
public:
int myAtoi(string str)
{
return atoi(str.c_str());
}
};
下面是AC的代码:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
class Solution
{
public:
int myAtoi(string str)
{
if (str.empty())
return 0;
int sign = 1, base = 0, i = 0, n = str.size();
while (i < n && str[i] == ' ')
++i;
if (str[i] == '+' || str[i] == '-')
sign = (str[i++] == '+') ? 1 : -1;
while (i < n && str[i] >= '0' && str[i] <= '9')
{
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7))
return (sign == 1) ? INT_MAX : INT_MIN;
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
};