String to Integer (atoi)
来源:互联网 发布:光环国际大数据开发 编辑:程序博客网 时间:2024/05/17 23:29
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.
spoilers alert... click to show requirements for atoi.
Have you met this question in a real interview?
思路: 注意处理各种情况。处理顺序如下。
1. 前, 后面为空格
2. 首字母符号
3. 找到最后一位合法数字。
4. 长度是否超过10.
5. 从后往前, 每次乘10 相加
6. 注意检查超上下界。
7. 最后符号相乘。
public class Solution{public int atoi(String str) {// filter out all the whitespace characters until the first// non-whitespace character is foundint start = 0;str = str.trim();// filter out the beginning 0s if it's not a 0start = 0;while (start < str.length() - 1 && str.charAt(start) == '0') {start++;}str = str.substring(start);// handle the empty stringif (str.length() == 0) {return 0;}// truncate the signboolean negative = false;if (str.charAt(0) == '-') {negative = true;str = str.substring(1);} else if (str.charAt(0) == '+') {str = str.substring(1);}// filter out all the characters after the first integral partint end = 0;while (end < str.length()) {char c = str.charAt(end);if ('0' <= c && '9' >= c) {end++;} else {break;}}str = str.substring(0, end);// check if the string length is too longif (str.length() > 10) {if (negative)return Integer.MIN_VALUE;elsereturn Integer.MAX_VALUE;}// calculate the numeric value from the right to the leftint ret = 0;int increment = 0;int digit = 1;for (int i = str.length() - 1; i >= 0; i--) {char c = str.charAt(i);increment = (str.charAt(i) - '0') * digit;//Check the integer range.if (!negative) {// if out of the positive integer rangeif (Integer.MAX_VALUE - ret - increment < 0) {return Integer.MAX_VALUE;}} else {// if out of the negative integer rangeif (Integer.MIN_VALUE + ret + increment > 0) {return Integer.MIN_VALUE;}}ret += increment;digit *= 10;}if (negative) {ret *= -1;}return ret;}}
0 0
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer(atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- 怎么追踪手机号码的位置
- 停车宝怎么用
- launcher3桌面阴影和systemUI阴影
- Technical Settings for the Workload Monitor
- release版本程序调用libvlc接口出现异常
- String to Integer (atoi)
- 算法导论第12章 红黑树
- 程序错误及故障分析(指针问题导致)
- zoj 1090 The Circumference of the Circle
- 反编译工具jad的使用
- nginx缓存过期管理小结
- POJ1273(最大流入门)
- Android实现左右滑动滑屏的功能
- 好站分享-互联网行业优秀网站分享、干货超多