zoukankan      html  css  js  c++  java
  • LeetCode(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 as 00111001011110000010100101000000).

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

    Related problem: Reverse Integer

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

    分析

    题目要求将一个32位无符号整数对应的二进制串反转,求翻转后的二进制串对应的新的32位无符号整数值。

    也就是说,只要我们求得该输入无符号整数的二进制表示形式,将其反转,再转换为十进制即可。

    注意的问题,题目明确要求了32位,也就是说对于整数的二进制串必然长度为32,若长度不足则用0补齐。处理后再反转,求新的十进制。

    另外,对于此题,我们还需要想到用位运算处理来提高运算速度。

    AC代码

    
    class Solution {
    public:
        //方法一
        uint32_t reverseBits(uint32_t n) {
            vector<int> bits;
            //利用位运算求二进制序列
            while (n)
            {
                bits.push_back(n & 1);
                n = n>> 1;
            }
    
            //求二进制位反转后对应的十进制数,若bits中长度不足32,以0步之
            uint32_t ret = 0;
            int size = bits.size();
            for (int i = 0 ; i <size; ++i)
            {
                ret = ret + bits[i] * (1 << (32 - i - 1));
            }//for
            return ret;
    
        }
    
        //简洁的解法2
        uint32_t reverseBits2(uint32_t n) {
             uint32_t res = 0;
             for (int i = 0; i < 32; ++i) {
                 res |= (((n >> i) & 1) << (31 - i));
    
            }
             return res;
        }
    };
    

    GitHub测试程序源码

  • 相关阅读:
    0601 新的冲刺
    0527 演示内容
    0525 项目回顾7.0
    0523 Scrum项目6.0
    0518 Scrum项目5.0
    Scrum 4.0
    0512 操作系统进程调度实验
    0511 backlog 项目管理
    复利计算器之单元测试
    操作系统的实验一实验报告
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214776.html
Copyright © 2011-2022 走看看