您的位置:首页 > 其它

[Leetcode #8]String to Integer (atoi) 字符串转整数

2016-08-23 12:14 369 查看
原题地址:https://leetcode.com/problems/string-to-integer-atoi/

题目要求是:给定一个字符串,转换为整数并返回,如无法转换则返回0。该字符串:

1. 可能为空串

2. 头部可能包含多个空格

3. 可能包含正负号

4. 转换过程中如果遇到除数字和正负号字符以外的字符,终止转换

5. 如果超出整数范围,返回INT_MAX或者INT_MIN

题目比较简单,上面这5种情况按顺序处理一下就可以了。用了一个比较偷懒的做法,计算结果是用long型保存的,这样就可以在计算完成之后判断是否溢出。如果使用int型的话,需要在计算之前判断是否溢出。

具体代码实现:

public class Solution {
public int myAtoi(String str) {
// check empty string
if (str == null || str.length() == 0) {
return 0;
}

int i = 0;
long result = 0;
int sign = 1;
char c;

// remove white spaces
while (i < str.length() && Character.isSpaceChar(str.charAt(i))) {
i++;
}

// handle signs
if (i < str.length() && (str.charAt(i) == '+' || str.charAt(i) == '-')) {
sign = (str.charAt(i) == '+' ? 1 : -1);
i++;
}

// convert digits
while (i < str.length()) {
c = str.charAt(i);
if (Character.isDigit(c)) {
result = result * 10 + (c - '0');
i++;
} else {
// invalid character
break;
}

if (result > Integer.MAX_VALUE) {
break;
}
}

// check overflow
result *= sign;
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}

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