zoukankan      html  css  js  c++  java
  • lc面试准备:Reverse Bits

    1 题目

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

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

    Related problem: Reverse Integer

    接口

    public int reverseBits(int n)
    uint32_t reverseBits(uint32_t n)

    2 思路

    简单写一下,Java的思路。Java中是没有无符号整数的,只有有符号的int(0x80000000 ~ 0x7fffffff)。

    &和|操作的结合使用。

    复杂度

    Time: O(n)  Space: O(1)

    3 代码

    1     public int reverseBits(int n) {
    2         int res = 0;
    3         for (int i = 0; i < 32; i++) {
    4             int bit = (n >> i) & 1;
    5             res |= bit << (31 - i);
    6         }
    7         return res;
    8     }

    4 总结

    (n >> i) & 1是取余数的好方法,不用借助额外的空间。

    5 参考

    1. leetcode
    2. stackoverflow
    3. Leetcode: Reverse Bits
  • 相关阅读:
    C语言01
    C++面试总结更新
    Python网络爬虫与信息提取02
    Self-Driving Car 01
    Python网络爬虫与信息提取01
    Python-03
    Shell
    Python-05
    Python-04
    Python-02
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4399327.html
Copyright © 2011-2022 走看看