/**
* 题目:把字符串转换成整数。 eg:+2147483647 1a33 返回:2147483647 0
*
* @author hexiaoli
*/
public class Main {
public static boolean flag;
public static int StrToInt(String str) {
flag = false;// 判断输入是否合法
if (str == null || str.length() == 0) {
flag = true;
return 0;
} // symbol=0,说明该数为正数;symbol=1,该数为负数;start用来区分第一位是否为符号位
int symbol = 0;
int start = 0;
char[] chars = str.toCharArray();
if (chars[0] == '+') {
start = 1;
} else if (chars[0] == '-') {
start = 1;
symbol = 1;
}
int result = 0;
for (int i = start; i < str.length(); i++) {
if (chars[i] > '9' || chars[i] < '0') {
flag = true;
return 0;
}
result = result * 10 + (int) (chars[i] - '0');
} // 注意:java中-1的n次方不能用:(-1)^n .'^'异或运算
result = (symbol == 0 ? result : -result);
return result;// 注意,当value=-2147483648时,value=-value
}
public static void main(String[] args) {
System.out.println(StrToInt("+2147483647"));
System.out.println(StrToInt("1a33"));
}
}