week7

来源:互联网 发布:货运物流软件 编辑:程序博客网 时间:2024/06/06 08:38

190. Reverse Bits          

题目:

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).

分析:输入一个数字,输出其二进制反向后的数字。最简单的方法是建立一个32位数字0,每次向左平移一位后与原数字的对应位置取或。为了取到原数字的那一位,需要用一个平移后的1与原数字取与。


代码:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t res = 0;
        uint32_t temp = 1;
        for (int i = 0; i < 32; i++) {
            res = (res<<1 )|((n&temp)>>i);
            temp= temp<<1;
        }
        return res;
    }
};


网上还有一种看起来很像加密技术的做法,我还在学习……

原创粉丝点击