算法系列——Number of 1 Bits

来源:互联网 发布:html input value js 编辑:程序博客网 时间:2024/06/05 09:01

题目描述

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

解题思路

考察位操作,二进制位 0或1 与1 进行& 与操作 得到它本身。
0&1=0 1&1=1
然后右移操作可以得到 二进位的下一位, 例如 111>>>1=011
011&001=001
结合与操作和移位操作 可以得到所有1的个数。

程序实现

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int count=0;        while(n!=0){            count+=n&1;            //>>>  无符号右移,忽略符号位,空位都以0补齐            n>>>=1;        }        return count;    }}
原创粉丝点击