码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Reverse Bits

时间:2015-04-21 11:11:36      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目:
Reverse bits of a given 32 bits unsigned integer.

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

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

思路分析:
从右到左取出每一位的数字,然后从左到右放置!注意位运算的神奇之处!

C++参考代码:

class Solution
{
public:
    uint32_t reverseBits(uint32_t n)
    {
        uint32_t result = 0;
        for (int i = 0; i < 32; ++i)
        {
            result <<= 1;//结果每次先左移一位,这样每次后面的数字 就能向前走一位
            if (n & 1) result |= 1;//如果n的末尾是1,则在result的后面修改为1
            //其实这里换成result ^= 1也是没问题的,因为0|1=1,0^1=1
            n >>= 1;//n右移,用于从右到左每次取后面的数字
        }
        return result;
    }
};

因为C++整形数据所占的字节数会随着机器的不同而稍微有些区别,如果题目没有说明给定的无符号整形是4个字节,32位呢?我们可以通过数字1左移判断无符号整形的字节数。

C++参考代码:

class Solution
{
public:
    unsigned int reverseBits(unsigned int n)
    {
        unsigned int result = 0;
        //通过1左移判断无符号整形的字节数
        for (int i = 1; i != 0; i <<= 1)
        {
            result <<= 1;
            if (n & 1) result |= 1;
            n >>= 1;
        }
        return result;
    }
};

Leetcode: Reverse Bits

标签:leetcode

原文地址:http://blog.csdn.net/theonegis/article/details/45167667

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!