关于java:面试题-String-23578-转int类型

1次阅读

共计 730 个字符,预计需要花费 2 分钟才能阅读完成。

给一个 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;
}

有问题能够留言哦,或者关注公众号(回复快):

正文完
 0