https://oj.leetcode.com/problems/string-to-integer-atoi/
http://fisherlei.blogspot.com/2013/01/leetcode-string-to-integer-atoi.html
public class Solution {
public int atoi(String str) {
// Validations
if (str == null || str.length() == 0)
return 0;
char[] chars = str.trim().toCharArray();
int len = chars.length;
int i = 0;
// Check +/-
boolean negative = false;
if (chars[0] == ‘+‘)
{
i++;
}
else if (chars[0] == ‘-‘)
{
negative = true;
i ++;
}
double result = 0;
for (; i < len ; i ++)
{
char c = chars[i];
if (c >= ‘0‘ && c <= ‘9‘)
result = result * 10 + (c - ‘0‘);
else
break; // Break the loop when meeting invalid chars.
}
if (negative)
result = -result;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int)result;
}
}[LeetCode]8 String to Integer (atoi)
原文:http://7371901.blog.51cto.com/7361901/1598404