栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计数int中使用的位

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计数int中使用的位

最简单?

32 - Integer.numberOfLeadingZeros(value)

如果您正在寻找算法,则Java API的实现者同意您的分而治之移位方法:

public static int numberOfLeadingZeros(int i) {    if (i == 0)        return 32;    int n = 1;    if (i >>> 16 == 0) { n += 16; i <<= 16; }    if (i >>> 24 == 0) { n +=  8; i <<=  8; }    if (i >>> 28 == 0) { n +=  4; i <<=  4; }    if (i >>> 30 == 0) { n +=  2; i <<=  2; }    n -= i >>> 31;    return n;}

编辑 :为了提醒那些相信浮点计算的准确性的人,请运行以下测试工具:

public static void main(String[] args) {    for (int i = 0; i < 64; i++) {        long x = 1L << i;        check(x);        check(x-1);    }}static void check(long x) {    int correct = 64 - Long.numberOfLeadingZeros(x);    int floated = (int) (1 + Math.floor(Math.log(x) / Math.log(2)));    if (floated != correct) {        System.out.println(Long.toString(x, 16) + " " + correct + " " + floated);    }}

检测到的第一个偏差是:

ffffffffffff 48 49


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508680.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号