题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
思路分析
- 逐个字符判断,如果是数字字符,则继续,否则返回0.
- 注意首字符有可能为 ‘+’、’-‘符号,特殊处理,并标记,返回的时候区分正负数。
代码实现
public class Solution {
public static int StrToInt(String str) {
if(str == null || str.length() == 0){
return 0;
}
int length = str.length();
int result = 0;
boolean positive = true;
for(int i=0; i < length; i++){
if(i == 0 && str.charAt(i) == '+'){
continue;
}
if(i == 0 && str.charAt(i) == '-'){
positive = false;
continue;
}
if(!isDigit(str.charAt(i))){
return 0;
}
result = result * 10 + (str.charAt(i) - '0');
}
return positive ? result : -result;
}
private static boolean isDigit(char num){
if(num >= '0' && num <= '9'){
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(StrToInt("-123"));
}
}