题解 | #把字符串转换成整数#
把字符串转换成整数
http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
思路:遍历字符串,遇到合法的字符直接转换成对应整数对接到当前前缀数上,不合法直接返回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;
}
}
美团成长空间 2638人发布
查看8道真题和解析