思路:遍历字符串,遇到合法的字符直接转换成对应整数对接到当前前缀数上,不合法直接返回0,最后返回结果数
注意:当前合法字符-'0'即可得到对应整数
public class Solution { public int StrToInt(String str) { if(str.length()==0){ return 0; } int res=0; //遍历字符串 遇到 不合法的 直接返回 -1 合法则直接转化为对应整数接到当前前缀数上 for (int i = 0; i <str.length(); i++) { if((str.charAt(i)=='+'||str.charAt(i)=='-')&&i==0){ continue; } if(str.charAt(i)-'0'>9 || str.charAt(i)-'0'<0){ return 0; } else { res=res*10+(str.charAt(i)-'0'); } } if(str.charAt(0)=='-'){ return -res; } return res; } }