LeetCode简单题:190. 颠倒二进制位(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/reverse-bits/
要点:位运算,分治法
可以像C++中所示用朴素的循环位运算解法做。
也可以像题解中巧妙分治法做,见下面链接。
举个例子:
// 原数字43261596
0000 0010 1001 0100 _ 0001 1110 1001 1100
// 反转左右16位:
0001 1110 1001 1100 _ 0000 0010 1001 0100
// 继续分为8位一组反转:
1001 1100 0001 1110 _ 1001 0100 0000 0010
// 4位一组反转:
1100 1001 1110 0001 _ 0100 1001 0010 0000
// 2位一组反转:
0011 0110 1011 0100 _ 0001 0110 1000 0000
// 每两位再反转一下
0011 1001 0111 1000 _ 0010 1001 0100 0000
// 这就是43261596反转后的结果:964176192
这里引用LeetCode作者:lartecy的解释
链接:https://leetcode-cn.com/problems/reverse-bits/solution/zhi-qi-ran-zhi-qi-suo-yi-ran-wei-yun-suan-jie-fa-x/

二.Python实现

class Solution:
    def reverseBits(self, n: int) -> int:
        n = (n >> 16) | (n << 16)
        n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
        n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
        n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
        n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
        return n

三.C++实现

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t ans=0;
        int i=32;
        while(i>0)
        {
            ans<<=1;
            ans+=n&1;
            n>>=1;
            i--;
        }
        return ans;
    }

};

四.java实现

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
         n = (n >>> 16) | (n << 16); 
        n = ((n & 0xff00ff00) >>> 8) | ((n & 0x00ff00ff) << 8); 
        n = ((n & 0xf0f0f0f0) >>> 4) | ((n & 0x0f0f0f0f) << 4); 
        n = ((n & 0xcccccccc) >>> 2) | ((n & 0x33333333) << 2); 
        n = ((n & 0xaaaaaaaa) >>> 1) | ((n & 0x55555555) << 1); 
        return n;    
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容