LeetCode //C - 190. Reverse Bits

190. Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

Note:

  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Example 1:

Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Constraints:
  • The input must be a binary string of length 32

From: LeetCode

Link: 190. Reverse Bits


Solution:

Ideas:
  • Initializes a result variable reversed to 0.
  • Iterates 32 times, corresponding to the 32 bits of an unsigned integer.
  • In each iteration, it shifts reversed to the left to make room for the next bit.
  • It then takes the least significant bit of n by performing n & 1 and ORs it with reversed.
  • Then it shifts n to the right by one, to process the next bit in the next iteration.
Code:
c 复制代码
uint32_t reverseBits(uint32_t n) {
    uint32_t reversed = 0;
    for (int i = 0; i < 32; i++) {
        reversed = (reversed << 1) | (n & 1);
        n >>= 1;
    }
    return reversed;
}
相关推荐
学习中.........19 分钟前
Karpathy nanoGPT 教程到底讲了什么
人工智能·算法·语言模型
城管不管34 分钟前
重生——第十次面试之开源中国一面挂
java·linux·开发语言·算法·面试·职场和发展·开源
YSL0701241 小时前
动态内存管理
c语言
地平线开发者2 小时前
征程6|YOLOv5x 在 Horizon 征程6 上的端到端部署实践(下)
算法·自动驾驶
BreezeJuvenile2 小时前
基于C语言的SPSC环形缓冲区程序实现
c语言·环形缓冲区
SuperByteMaster2 小时前
recursive mutex的使用场景和场景代码
c语言
speop2 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
艾为电子2 小时前
【应用方案】电视沉浸式音频升级: 电视音频 awinic“芯片 + 算法” 一体化解决方案
算法·音视频
大熊背2 小时前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_3 小时前
面试Leetcode - 算法合集
算法·leetcode·面试