码迷,mamicode.com
首页 > 其他好文 > 详细

不使用JDK的方法自己实现字符串转整数

时间:2017-12-27 02:39:19      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:string   符号   form   +=   nbsp   value   数字   ber   for   

暂未考虑正负符号的情况。

    public static int parseInt(String str) {
        if (str == null || str.trim() == "") throw new NumberFormatException("For input string:" + str);
        char[] chars = str.toCharArray();
        long result = 0;
        for (int i = 0; i < chars.length; i++) {
//是否是‘0‘到‘9‘之间的字符
if (chars[i] < ‘0‘ || chars[i] > ‘9‘) throw new NumberFormatException("For input string:" + str);
//先根据字符之间进行运算来得到int值,再根据每个数字所在的位数来计算应该乘10的几次幂,最后累加。比如【3256=3*1000+2*100+5*10+6】 result
+= (chars[i] - ‘0‘) * Math.pow(10, chars.length - i - 1) ; }
//是否超出int的最大值
if (result > Integer.MAX_VALUE) throw new NumberFormatException("For input string:" + str); return (int) result; }

 

不使用JDK的方法自己实现字符串转整数

标签:string   符号   form   +=   nbsp   value   数字   ber   for   

原文地址:https://www.cnblogs.com/jun1019/p/8120829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!