剑指Offer(Java版)第五十五题:将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

/*
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
数值为0或者字符串不是一个合法的数值则返回0
*/
//输入一个字符串,包括数字字母符号,可以为空
//如果是合法的数值表达则返回该数字,否则返回0
//输入:
//+2147483647
//1a33
//输出:
//2147483647
//0
public class Class55 {

public int StrToInt(String str){
if(str == null || str.length() == 0 || str == " "){
return 0;
}
char[] ch = str.toCharArray();
int index = 0;
int i = 0;
if(ch[0] == '+'){
index = 1;
i = 1;
}
if(ch[0] == '-'){
index = -1;
i = 1;
}
int sum = 0;
for(; i < ch.length; i++){
if(ch[i] >= 48 && ch[i] <= 57){ //ASCII码
sum = sum * 10 + ch[i] - 48;
}else{
return 0;
}
}
if(index == 1){
return sum;
}
if(index == -1){
return sum = sum * (-1);
}
return sum;
}

public void test(){
String str = "-2147483647";
System.out.println(StrToInt(str));
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Class55 c = new Class55();
c.test();

}

}

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12535472.html