首页 > 其他 > 详细

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

时间:2017-12-27 01:13:13      阅读:230      评论:0      收藏:0      [点我收藏+]

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

    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的方法自己实现字符串转整数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!