Java中i& =(i-1)的含义是什么 [英] what is the means of i &=(i-1) in java

查看:320
本文介绍了Java中i& =(i-1)的含义是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    int n;
    for ( n = 0; i >0; n++)
    {
        i &= (i-1);
    }
    return n;

//也许它的功能是计算1的数量,我不知道句子的意思

//maybe its function is to count the number of 1, I don't know the sentence means

推荐答案

&是Java中的按位AND运算.此函数正在计算达到0所需的运算数量.

& is the bitwise AND operation in Java. What this function is doing is counting the number of those operations it take to reach 0.

此函数正在对数字的二进制表示形式中的"1"进行计数(一些研究使我得以找到

This function is counting the number of "1's" in a binary representation of a number (a bit of research allowed me to find this). The way this works is it flips the rightmost bit that is 1 on every pass in the loop until the number is zero.

例如,如果我们在100上运行此函数:

For instance, if we run this function on 100:

1100100 & 1100011 = 1100000 //Flipped the rightmost one bit (100 & 99)
1100000 & 1011111 = 1000000 //Then the next (96 & 95)
1000000 & 0111111 = 0000000 //And finally the last (64 & 63)

因此循环将执行3次,表示数字100中的3个"on"位.

So the loop will have executed 3 times, indicating 3 "on" bits in the number 100.

这篇关于Java中i& =(i-1)的含义是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆