题目要求:
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.
这是LeetCode中的第8题,剑指offer中涉及到的一道面试题,将String转化为Integer型,看似很简单,但是需要考虑的情况很多,需要比较细心。
首先字符串转换中遇见非数字字符的处理,字符串超出最大整型和最小整型怎么处理。开题遇到空格,用trim()去空格。+,-号只可能在去空格后第一位。中间遇到非数字字符,直接返回前一段字符,判断是否有效,并转换为整型。
代码如下:
/**
* 将字符串转化为整数
* @congrisheng
* @2017-3-12
*/
public static int StrToInt(String str){
/*定义最大最小边界值*/
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
if(str == null || str.length() == 0){
return 0;
}
/*去掉字符串首尾的空格*/
str = str.trim();
/*如果首位是+,- 作为整数的符号*/
boolean sign = false;
if(str.charAt(0) == '-' || str.charAt(0) == '+'){
if(str.charAt(0) == '-'){
sign = true;
}
str = str.substring(1);
}
int len = str.length();
/*定义为long型去储存结果*/
long res = 0;
for(int i = 0; i < len; i++){
char s = str.charAt(i);
/*不是整数就中断*/
if(s < '0' || s > '9'){
break;
}
/*转换*/
res = res*10 + (s - '0');
/*超过阈值直接return*/
if(!sign && res > max){
return max;
}
if(sign && -res < min){
return min;
}
}
if(sign){
res = -res;
}
/*转换为int型的数*/
return (int)res;
}
From 《剑指offer》 Page12