1.输入一个表示整数的字符串,把该字符串转换成整数并输出
public static int atoi(String str) {
int neg = 0;
int i = 0;
if (str.charAt(i) == '-') {
i++;
neg = 1;
} else if (str.charAt(i) == '+') {
i++;
}
int num=0;
while (i < str.length()) {
int tmp = str.charAt(i) - '0';
if (tmp >= 0 && tmp <= 9) {
num = num * 10 + tmp;
} else {
System.err.println("illegal number");
}
i++;
}
if (neg == 1)
num = 0-num;
return num;
}
问题描述:
输入:“-42” 输出:-42
输入:“42 ” 输出:42
输入:“4193 with words” 输出:4193
输入:“words and 987” 输出:0
输入:“-91283472332” 输出:2147483648
public static int myAtoi(String str){
boolean flag_positive = true;
char tmp_c;
long r = 0;
if(null == str || (str = str.trim()).length() ==0) return 0;
if(str.startsWith("-")|| str.startsWith("+")){
if(str.startsWith("-"))
flag_positive = false;
str = str.substring(1);
}
if(str.length() == 0 || !((tmp_c = str.charAt(0)) >='0' && tmp_c <= '9')) return 0;
for(int i = 0, tmp_i = 0, max = str.length(); i < max &&((tmp_c = str.charAt(i)) >='0' && tmp_c <= '9');i++){
tmp_i = Integer.parseInt(tmp_c + "");
r = r * 10 + tmp_i;
if(r>Integer.MAX_VALUE){
return flag_positive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
}
return (int) (flag_positive ? r : -r);
}