import java.util.ArrayList;
public class Solution {
public int StrToInt(String str) {
//思路:遍历一遍每个字符
//如果其中包含字母、以及其它符号,则直接返回0
//这里有一种特殊的情况时,+或-在最前面的时候,也是合法的
//关键是:要想到用字符的ASCII码进行判断
if(str==null||str.length()==0){
return 0;
}
//这个标记位是为了最后区分正负值用
int flag = 1;
char[] cs = str.toCharArray();
//下面这一段用来处理+-开头的特殊情况
if(cs[0] =='-'){
flag = -1;
cs[0] = '0';
}
if(cs[0] =='+'){
cs[0] = '0';
}
ArrayList<Integer> list = new ArrayList<>();
//先遍历一遍,把数据放入一个list中
//这里的关键是:用这个(int)c - (int)('0') 将字符转换为数字
for(char c : cs ){
if(c < 48|| c > 57){
return 0;
}
else{
list.add((int)c - (int)('0'));
}
}
int res = 0;
int length = list.size();
//用十进制表示法,个位*10的0次方,十位乘以10的1次方,以此类推
for(int i : list){
res = res + i * (int)Math.pow(10,--length);
}
//乘以正负值
return res * flag;
}
}