题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
主要考虑边界条件
public class Solution {
public int StrToInt(String str) {
if (str == null || str.length() == 0) {
return 0;
}
int result = 0;
int i = 0, len = str.length();
boolean negative = false;
char fistc = str.charAt(0);
if(fistc == '-'){
negative = true;
i++;
}else if(fistc == '+') i++;
else if(fistc < '0' || fistc > '9') return 0;
while(i < len){
if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
int temp = str.charAt(i++) - '0';
result = result * 10;
result = result + temp;
}else return 0;
}
return negative ? -result : result;
}}