题目链接:https://leetcode.com/problems/string-to-integer-atoi/
题目:
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.
思路:
各种边界会烦死人的。。。
算法:
-
public int myAtoi(String str) {
-
if (str == null || str.equals(""))
-
return 0;
-
str = str.trim();
-
String flag = "+";
-
int i = 0;
-
if ("+".equals(str.charAt(0) + "")) {
-
i++;
-
flag = "+";
-
} else if ("-".equals(str.charAt(0) + "")) {
-
i++;
-
flag = "-";
-
}
-
double sum = 0;
-
while (i < str.length() && str.charAt(i) <= ‘9‘ && str.charAt(i) >= ‘0‘) {
-
sum = sum * 10 + Integer.parseInt("" + str.charAt(i));
-
i++;
-
}
-
if (flag.equals("-")) {
-
sum = -sum;
-
}
-
if (sum > Integer.MAX_VALUE) {
-
sum = Integer.MAX_VALUE;
-
}
-
if (sum < Integer.MIN_VALUE) {
-
sum = Integer.MIN_VALUE;
-
}
-
return (int) sum;
-
}
【Leetcode】String to Integer (atoi)
原文:http://blog.csdn.net/yeqiuzs/article/details/51598065