`

Count the number of set bits in an integer

 
阅读更多

Question: Count the number of set bits in an 32 integer. 

 

Method 1:

Count the bit one by one, 这显然不好:

public int bitCount(int a) {
    int num = 0;
    for (int i=0; i<32; ++i) {
        if ((a & (1<<i)) != 0)
            num++;
    }
    return num;
}

 

Method 2:

仅查被set的位。

public int bitCount(int n) {
	int count = 0; 
	while(n != 0){ 
		count++; 
		n &= n-1; 
	} 
	return count;
}

 

Method 3:

注意Java里面要用>>>,代表把符号一块儿右移。

public int bitCount(int a) {
    a = ((0xAAAAAAAA & a)>>>1) + (0x55555555 & a);
    a = ((0xCCCCCCCC & a)>>>2) + (0x33333333 & a);
    a = ((0xF0F0F0F0 & a)>>>4) + (0x0F0F0F0F & a);
    a = ((0xFF00FF00 & a)>>>8) + (0x00FF00FF & a);
    a = ((0xFFFF0000 & a)>>>16) + (0x0000FFFF & a);
    return a;
}

 

Method 4:

上面的方法还可以改进为下面这样,方便好记。

public int bitCount(int n) {
    n = (n & 0x55555555) + ((n>>>1) & 0x55555555);
    n = (n & 0x33333333) + ((n>>>2) & 0x33333333);
    n = (n & 0x0F0F0F0F) + ((n>>>4) & 0x0F0F0F0F);
    n = (n & 0x00FF00FF) + ((n>>>8) & 0x00FF00FF);
    n = (n & 0x0000FFFF) + ((n>>>16) & 0x0000FFFF);
    return n;
}

 

Method 5:

Hacker's Delight里的方法,也是Java源码的实现方法。

public int bitCount(int i) {
    // HD, Figure 5-2
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}

 

分享到:
评论

相关推荐

    A.Collection.of.Bit.Programming.Interview.Questions.solved.in.C++

    Count the number of bits set in an unsigned number Chapter 9. Add two numbers without using arithmetic operators Chapter 10. Given an array of integers where all the numbers are appearing twice find ...

    php.ini-development

    The number of significant digits displayed in floating point numbers. ; http://php.net/precision precision = 14 ; Output buffering is a mechanism for controlling how much output data ; (excluding ...

    acpi控制笔记本风扇转速

    Added the AcpiGpeCount global that tracks the number of processed GPEs, to be used for debugging systems with a large number of ACPI interrupts. Implemented support for the "DMAR" ACPI table (DMA ...

    Company-Wise-Coding-Questions

    ===========公司明智的编码问题============= ...9. Prime Number of Set Bits 10. Reverse Each Word in String 11. Find k-th character in string 12. Star Elements 13. Common Subsequence 14. Choco

    Itanium Architecture For Programmers

    Review of Number Systems Summary References Exercises Chapter 2. Computer Structures and Data Representations Section 2.1. Computer Structures Section 2.2. Instruction Execution ...

    Bochs - The cross platform IA-32 (x86) emulator

    - Fix BIOS INT13 function 08 when the number of cylinders on the disk = 1 - I/O Devices - USB HP DeskJet 920C printer device emulation (Ben Lunt) - Misc - Updated Bochs TESTFORM to version 0.5 -...

    GifDecoder

    * Gets the number of frames read from file. * @return frame count */ public int getFrameCount() { return frameCount; } /** * Gets the number of frames read from file. * @return frame count *...

    A Collection of Bit Programming Interview Questions solved in C++.pdf

    int count_set_bits(unsigned int n) { int count = 0; while (n &gt; 0) { count += n & 1; n &gt;&gt;= 1; } return count; } ``` #### 9. 不使用算术运算符加两个数 **问题描述:** 给定两个无符号整数,不使用任何...

    LeetCode最全代码

    421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/...

    MySql 参考手册

    - `EXPORT_SET(bits, on, off, [separator], [number_of_bits])`:根据 bits 创建一个由 separator 分隔的字符串。 - `FIELD(str, str1, str2, str3, ...)`:返回 str 在 str1、str2、str3 等字符串中的位置。 - ...

    算法-leetcode-剑指offer上的题很多

    - **找出不快乐的数字(Find the Unhappy Number)**: 判断一个数字是否会在特定的操作中进入无限循环。 以上就是文档内容中所涉及的算法知识点,其中涵盖了数据结构基础、排序算法、搜索技巧、数学问题解决以及动态...

Global site tag (gtag.js) - Google Analytics