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

面试题 String “1247" 转int类型

时间:2021-04-06 14:52:01      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:form   数字   ber   new   string   int()   exception   this   valueof   

给一个String str="123"; 转成int类型数据

面试的时候问这个问题,可能考察的不仅仅是parseInt()、valueOf()、intValue等方法

这个面试官想要的答案我也没不明白 这里写几种转换方式(转换时不考虑字符串非数字)

一、parseInt

public int String2Int01(String str){
       return  Integer.parseInt(str);
}

二、valueOf intValue

 public int String2Int02(String str){
        return  Integer.valueOf(str).intValue();
 }

三、 new Integer(String str)

public int String2Int03(String str){
        return  new Integer(str).intValue();
}
// 可以看源码 用的还是parseInt()
 public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
 }

四、转数组 再位数求和

public int String2Int04(String str){
        char[] chars = str.toCharArray();
        int res = 0;
        int basic= 1;// 基数1 每次累计*10 
        // 比如 123  分解开就是 3*1 + 2*10 + 1*100
        for (int i = chars.length-1; i >= 0; i--) {
            // - ‘0‘ 是把char转换为0-9s
            res= res + (chars[i]-‘0‘)*basic;
            basic = basic*10;
        }
        return res;
}

面试题 String “1247" 转int类型

标签:form   数字   ber   new   string   int()   exception   this   valueof   

原文地址:https://www.cnblogs.com/freeedu/p/14616680.html

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