[LeetCode刷题记录]190-191 Number of 1 Bits & Reverse Bits

本文深入解析了二进制中求1的个数(汉明重量)、正整数翻转位以及32位无符号整数翻转的算法实现,并通过实例代码演示了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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.

分析:这个题目是求一个正整数用二进制表示后其中的1的个数。看到题目后不难想到只要让其循环移位,每次和0x01做与操作,统计1的个数即可。

这样我们可以很快的写出代码。

<pre name="code" class="cpp"><span style="font-size:12px;">class Solution {
public:
    int hammingWeight(uint32_t n) {
        int result = 0;
        while(n!=0)
        {
            if(n&0x01)
            ++result;
            n = n>>1;
        }
        return result;
    }
};</span>

 
代码中有两点要注意:1)移位符代替除法效率要高;2)这种方法只适合于正整数情况。 

在《剑指Offer》中有相同的题目,它对负数的情况也进行讨论。负数右移的时候,最高位符号保持不变。比如0x80000000右移一位的结果就是0xC0000000;如果这个循环持续进行,最后结果在0xFFFFFFFF,程序陷入死循环。

更好的改进方法是对0x01进行移位,然后对其做与,来计算为1的个数。

<pre name="code" class="cpp">class Solution {
public:
    int hammingWeight(uint32_t n) {
        int result = 0;
            unsigned int flag = 0;
        while(flag!=0)
        {
            if(n&flag)
                  ++result;
            flag = flag <<1;
        }
        return result;
    }
};


 

书中还给了另一种解法。

基于这样的事实:把一个整数减去1,再和原整数做与运算,会每次把整数最右边的第一个1变成0。一个数中有多少个1就可以做多少次这样的操作。我们可以把代码进一步改为:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int result = 0;
            unsigned int flag = 0;
        while(flag!=0)
        {
            if(n&flag)
                  ++result;
            flag = flag <<1;
        }
        return result;
    }
};


Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

分析:题目要求把一个正整数的每位Bit翻转。这个题目可以用到191题的思想,首先用0x01循环右移,同时0x80000000循环左移。在原数字某位为1的时候(做与运算),让左移翻转数字的同样位置置1(做或运算)即可。

代码如下:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t p1=0x01;
        uint32_t p2=0x80000000;
        uint32_t result=0;
        while(p1)
        {
            if(n&p1)
              result=result|p2;
            p1=p1<<1;
            p2=p2>>1;
        }
        return result;
    }
};





### LeetCode Top 100 Popular Problems LeetCode provides an extensive collection of algorithmic challenges designed to help developers prepare for technical interviews and enhance their problem-solving skills. The platform categorizes these problems based on popularity, difficulty level, and frequency asked during tech interviews. The following list represents a curated selection of the most frequently practiced 100 problems from LeetCode: #### Array &amp; String Manipulation 1. Two Sum[^2] 2. Add Two Numbers (Linked List)[^2] 3. Longest Substring Without Repeating Characters #### Dynamic Programming 4. Climbing Stairs 5. Coin Change 6. House Robber #### Depth-First Search (DFS) / Breadth-First Search (BFS) 7. Binary Tree Level Order Traversal[^3] 8. Surrounded Regions 9. Number of Islands #### Backtracking 10. Combination Sum 11. Subsets 12. Permutations #### Greedy Algorithms 13. Jump Game 14. Gas Station 15. Task Scheduler #### Sliding Window Technique 16. Minimum Size Subarray Sum 17. Longest Repeating Character Replacement #### Bit Manipulation 18. Single Number[^1] 19. Maximum Product of Word Lengths 20. Reverse Bits This list continues up until reaching approximately 100 items covering various categories including but not limited to Trees, Graphs, Sorting, Searching, Math, Design Patterns, etc.. Each category contains multiple representative questions that cover fundamental concepts as well as advanced techniques required by leading technology companies when conducting software engineering candidate assessments. For those interested in improving logical thinking through gaming activities outside traditional study methods, certain types of video games have been shown beneficial effects similar to engaging directly within competitive coding platforms [^4]. --related questions-- 1. How does participating in online coding competitions benefit personal development? 2. What specific advantages do DFS/BFS algorithms offer compared to other traversal strategies? 3. Can you provide examples illustrating how bit manipulation improves performance efficiency? 4. In what ways might regular participation in programming contests influence job interview success rates? 5. Are there any notable differences between solving problems on paper versus implementing solutions programmatically?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值