前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Reverse Bits

Leetcode: Reverse Bits

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:25:25
4340
发布2019-01-22 15:25:25
举报

题目: 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++参考代码:

代码语言:javascript
复制
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++参考代码:

代码语言:javascript
复制
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;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年04月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档