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.

Show Tags

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
原创粉丝点击