标签:ch return 48 int 整数 牛客 result str 字符串
题目描述:
代码:
//一
public class Main6 {
public int StrToInt(String str) {
//边界 空字符 “-” “+”
if(str.length()==0){
return 0;
}else if(str.length()==1&&(str.charAt(0)=='-'||str.charAt(0)=='+')){
return 0;
}else{
int flag=0;//区分正负 0为正数 1为负数
boolean error=false;
char[] ch=str.toCharArray();
int i=0;//索引
if (ch[0]=='-'){
i++;
flag=1;
}else if(ch[0]=='+'){
i++;
flag=0;
}
int result=0;//返回的结果
for (int j=i;j<ch.length;j++){
if (ch[j]>='0'&&ch[j]<='9'){
result=result*10+(ch[j]-'0');
}else{
error=true;
break;
}
}
if (!error){
if (flag==1){
result=result*(-1);
}
return result;
}else {
return 0;
}
}
}
}
public class Main {
//二
//利用ASIC码:数字0是48,9是57,char型比int型数字大48
public int StrToInt1(String str) {
char[] ch = str.toCharArray();
if (str.length() == 0) {
return 0;
}
int result = 0;
int m = 0;
for (int i = str.length() - 1; i >= 0; i--) {
//如果非数字和符号,直接return 0
if ((ch[i] < 48 || ch[i] > 57) && ch[i] != '-' && ch[i] != '+') {
return 0;
}
//如果是数字,就从低位到高位累加,每次扩大10倍
if (ch[i] >= 48 && ch[i] <= 57) {
result += (ch[i] - 48) * Math.pow(10, m++);
}
}
if (ch[0] == '-') {
return -result;//判断符号位
}
return result;
}
}
标签:ch,return,48,int,整数,牛客,result,str,字符串 来源: https://blog.csdn.net/weixin_45795182/article/details/123167861
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。