题目的链接在这里:https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
题目大意
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0一、示意图
二、解题思路
暴力
暴力
代码如下:
public class Solution {
public int StrToInt(String str) {
//把字符串转化为整数 如果数值为0或者不是一个合法的数值就返回0
char[] chars = str.toCharArray();
//然后就一个一个判断
int res=0;
boolean flag = false;
for(int i=0;i<chars.length;i++){
//直接进行计算好了
//还需要对第一个进行判断
if(i==0){
//要进行判断
if(chars[i]=='+'){
continue;
}
if(chars[i]=='-'){
//那就做一个标记
flag=true;
continue;
}
}
int temp=chars[i]-'0';
if(temp>9||temp<0){
return 0;
}
else{
//不然的话就进行计算
res*=10;
res+=temp;
}
}
return flag?-res:res;
}
}