您的位置:首页 > 其它

String to Integer

2016-07-23 05:22 260 查看
Implement function
atoi
to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values, INT_MAX(2147483647) or INT_MIN (-2147483648) is returned.

Example

"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1


public class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0)
return 0;
str = str.trim();
if (str.length() == 1 && (str.equals("+") || str.equals("-") || str.equals(".") || str.equals("0"))) {
return 0;
}

boolean isPositive = true;
long current = 0;

for (int i = 0; i < str.length(); i++) {
if (i == 0 && str.charAt(i) == '+') {
continue;
} else if (i == 0 && str.charAt(i) == '-') {
isPositive = false;
} else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
current = current * 10 + str.charAt(i) - '0';
if (isPositive && current > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (!isPositive && -current < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
} else {
break;
}
}

if (!isPositive) {
current = -current;
}

return (int) current;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: