Home Database Mysql Tutorial 【编程之美】2.1求二进制中1的个数

【编程之美】2.1求二进制中1的个数

Jun 07, 2016 pm 03:15 PM
number binary byte programming

题目: 对于一个字节的无符号整数变量,求其中的二进制表示中1的个数,要求算法执行效率尽可能高效。 题目解析: 这道题同样在【剑指offer】面试题10:二进制中1的个数中出现,不过在剑指offer中没有提到无符号数,因此比该题目中多考虑一个层次。下面总结这


题目:

对于一个字节的无符号整数变量,求其中的二进制表示中1的个数,要求算法执行效率尽可能高效。


题目解析:

这道题同样在【剑指offer】面试题10:二进制中1的个数 中出现,不过在剑指offer中没有提到无符号数,因此比该题目中多考虑一个层次。下面总结这道题的几种解法。


解法一(用于该题目):

我们通常会想到除以2就是将二进制右移一位,但要判断移除的是0还是1,就要对2取余。思路很简单,通过四则运算来解答:

int Count(Byte v)
{
    int num = 0;
    while(v){
        if(v%2)
            num++;
        v /= 2;
    }
    return num;
}
Copy after login

解法二(用于该题目)

对于除以2来表示二进制右移,除法的效率比直接移位的效率低得多。碰到这样的题目,尽量用移位来代替。位运算就五种形式:与、或、异或、左移和右移。在这些范围里面找到自己想要的运算。移位时要判断移除的是0还是1,那么这里就应该通过与操作判断最后一位是否为1。

int Count2(Byte v)
{
    int num = 0;
    while(v){
        if(v & 1)
            num++;
    //也可以用 num += v&1; 来代替上面两行
        v = v >> 1;
    }
    return num;
}
Copy after login

解法三(可以用于有符号数):

如果这个题目是有符号的话,当右移的时候,会在高位补充符号位,用上面两种方法的话,会陷入死循环。如何避免?可以先判断最高位,然后遍历n-1次判断除了最高位以外的位是否为1。这样的方法比较麻烦。我们可以变通一个思路,让与的那一位1不断的左移,直到将1移到最高位。

int Count3(Byte v)
{
    int num = 0;
    int flag = 1;
    while(flag){
        if(v & flag)
            ++num;
        flag = flag <br>
解法四(更加高效的算法):
<p><span><span>这种方法,充分利用了二进制的相关操作,平时应该多收集这样的运算。</span></span></p>
<p><span><span>一个数不为0,那么二进制中肯定含1。当让这个数减去1时,最低位的1由1->0,更低位的0由0->1。当让n与n-1相与以后,n中最低位的1变成0。一次这样的操作,消去一个1,那么二进制中有多少个1,就循环多少次即可。</span><br>
</span></p>
<p></p><pre class="brush:php;toolbar:false">int Count4(Byte v)
{
    int num = 0;
    while(v){
        ++num;
        v = v & (v-1);
    }
    return num;
}
Copy after login


解法五(空间换时间方法):

其实方法四已经够好了,但是因为只涉及到八位,我们可以利用选择直接选取相应的数据。比如0x1-0x2-0x4...这些都包含1个1;0x3-0x6...包含两个1;等等。通过switch语句选择相应的结果。但是这种方法效率可能比较低,因为,当输入v为255的时候,得比较到最后才能找到相应的数据。

int Count5(Byte v)
{
    int num = 0;
    switch(v){
    case 0x0:
        num = 0;
        break;
    case 0x1:
    case 0x2:
        ....
    }

    return num;
}
Copy after login

解法六(哈希表法):

既然想到了利用空间换时间,我们干脆用个数组来表示,index为要查找的数,counttable[index]为该数据包含1的个数。








Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Remove duplicate values ​​from PHP array using regular expressions Remove duplicate values ​​from PHP array using regular expressions Apr 26, 2024 pm 04:33 PM

How to remove duplicate values ​​from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

What is programming for and what is the use of learning it? What is programming for and what is the use of learning it? Apr 28, 2024 pm 01:34 PM

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

TikTok sues to challenge the Biden administration's divestiture bill: 'Sell or ban” violates the First Amendment of the U.S. Constitution TikTok sues to challenge the Biden administration's divestiture bill: 'Sell or ban” violates the First Amendment of the U.S. Constitution May 08, 2024 pm 02:01 PM

According to news from this site on May 8, TikTok filed a lawsuit in the U.S. Federal Court on Tuesday, challenging the Biden administration’s divestiture bill and asking the U.S. court to prevent the implementation of the bill. TikTok filed a lawsuit on Tuesday, claiming that Congress "took unprecedented measures to clearly single out and ban TikTok" and called the move "unconstitutional." According to reports, Beckman said that if the separation bill officially takes effect, TikTok will fight back in court. Beckman said that the "sell or ban" law "clearly violates" the First Amendment rights of TikTok's 170 million American users and will have "devastating consequences" for the 7 million small businesses on the platform. He also said, "This is the beginning of a long process, not the end" and "continue to fight." Related

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

How many transactions are there in one Ethereum block? How many bytes does it occupy? How many transactions are there in one Ethereum block? How many bytes does it occupy? Jun 10, 2024 pm 10:15 PM

When it comes to blockchain speed, the most intuitive comparison is the number of transactions per second. Ethereum is one of the most well-known blockchains at the moment, and its transaction volume is also very large. It is a decentralized computing platform based on blockchain technology, which allows developers to build and deploy smart contracts and decentralized Applications (DApps) and provide a secure, transparent, and tamper-proof computing environment. Not long ago, data announced that the SOL chain is the fastest, so how many transactions are there in one block of Ethereum? Arousing the curiosity of investors, according to the latest data, there are about 23 transactions per second in one Ethereum block. The editor below will tell you in detail. How many transactions are there in one Ethereum block? According to the latest data, there are about 23 transactions per second in an Ethereum block, but an Ethereum block contains

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

See all articles