String to Integer
2016-07-23 05:22
260 查看
Implement function
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
atoito 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; } }
相关文章推荐
- Singleton Pattern
- Fast Power
- Generate Parentheses
- 关于在MySQL中实现upsert操作
- 利用无线网卡建立个人wifi hotspot
- codeforces 701C They Are Everywhere(尺取法)
- POJ1328-Radar Installation
- 【CSS】其他CSS属性和特性
- ST表与二分 (CodeForces 689D-Friends and Subsequences)
- jvm 配置,看看
- Reverse Words in a String II
- Git命令小总结
- Unity各个函数的执行顺序
- Intersection of Two Arrays
- Codeforces Round #364 (Div. 2) 题解
- 面试基础
- 利用jar命令打包和解压
- JavaScript创建对象
- 【C++11】C++11新增的便利算法[1] all_of、any_of 和 none_of
- 暴力枚举,dfs(连连看,HDU 4272)