题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
输入描述:
复制代码
1输入一个字符串,包括数字字母符号,可以为空
输出描述:
复制代码
1如果是合法的数值表达则返回该数字,否则返回0
num+=(ch[i]-48)*(int)Math.pow(10, len-i-1);//一定要强制转换成int类型,要不然用double类型的数据计算会精度丢失
用字符做运算ch[i]-48 或者ch[i]-'0'
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public class Solution { public static int StrToInt(String str) { if(str.trim().equals("")) return 0; char[] ch=str.toCharArray(); int len=ch.length; int num=0; for(int i=1;i<len;i++){ if(ch[i]>='0' && ch[i]<='9'){ num+=(ch[i]-48)*(int)Math.pow(10, len-i-1); }else{ return 0; } } if(ch[0]=='+' )return num; if(ch[0]=='-' )return -num; if(ch[0]>='0' || ch[0]<='9')return num+=Math.pow(10, len-1)*(ch[0]-48); return 0; } }
最后
以上就是缓慢雨最近收集整理的关于把字符串转换成整数(char与int的转换)的全部内容,更多相关把字符串转换成整数(char与int内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复