记住步骤 将字符串转化为整数
将字符串转化为整数
http://www.nowcoder.com/questionTerminal/44d8c152c38f43a1b10e168018dcc13f
处理空字符串 忽略前置空格 保存符号 处理非法输入 处理溢出
import java.util.*;
public class Solution {
/**
*
* @param str string字符串
* @return int整型
*/
public int atoi (String str) {
// write code here
int res =0, symbol = 1, i = 0, n = 0;
if(str == null || str.equals(""))
return 0;
for(i = 0; str.charAt(i) != '\0' && str.charAt(i) == ' '; ++i){} //2.跳过前导空格
if(str.charAt(i) == '-' || str.charAt(i) == '+')
symbol = str.charAt(i++) != '-' ? 1 : -1;
for(; i < str.length() && Character.isDigit(str.charAt(i)); ){
n = (str.charAt(i++) - '0') * symbol;
if( (res > Integer.MAX_VALUE / 10) || (res == Integer.MAX_VALUE / 10 && n > Integer.MAX_VALUE % 10) ) { // 上溢出.
return Integer.MAX_VALUE ;
}
if( (res < Integer.MIN_VALUE / 10) || (res == Integer.MIN_VALUE / 10 && n < Integer.MIN_VALUE % 10) ) { // 下溢出.
return Integer.MIN_VALUE;
}
res = res * 10 + n;
}
return res;
}
}
查看9道真题和解析
腾讯成长空间 6074人发布