字符串转换整数 (atoi) (测试+代码)
package LeetCode;
class Solution {
public static void main(String[] args) {
int result= myAtoi("-422 word");
System.out.println(result);
}
public static int myAtoi(String str) {
if(str==null) return 0;
str=str.trim();
if(str.isEmpty()) return 0;
int index=0;
int sign=1; //给正负数做标记,而不要理解是正负参与运算,给正负数变号
char firstChar=str.charAt(0);
if(firstChar=='+'){ //满足条件进入
index++;
}else if(firstChar=='-'){
sign=-1;
index++;
}else if(!Character.isDigit(firstChar)){
return 0;
}
long num=0;
long res=num*sign;
while (index<str.length()&&Character.isDigit(str.charAt(index))) { //Character.isDigit(str.charAt(index) 当前的char要能转换为数字
num=num*10+Integer.parseInt(String.valueOf(str.charAt(index))); //char转化为string,然后通过Integer.parseInt接受,然后不断的递进++
res=num*sign;
if(res>Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (res<Integer.MIN_VALUE) return Integer.MIN_VALUE;
index++;
}
return (int)(num*sign);
}
}