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;
}
相关推荐
星星的月亮叫太阳1 小时前
large-scale-DRL-exploration 代码阅读 总结
python·算法
王哈哈^_^1 小时前
YOLOv11视觉检测实战:安全距离测算全解析
人工智能·数码相机·算法·yolo·计算机视觉·目标跟踪·视觉检测
..Cherry..1 小时前
Etcd详解(raft算法保证强一致性)
数据库·算法·etcd
商汤万象开发者1 小时前
LazyLLM教程 | 第13讲:RAG+多模态:图片、表格通吃的问答系统
人工智能·科技·算法·开源·多模态
Lee_yayayayaya2 小时前
本原多项式产生m序列的原理
算法
许长安2 小时前
c/c++ static关键字详解
c语言·c++·经验分享·笔记
蒙奇D索大3 小时前
【算法】递归的艺术:从本质思想到递归树,深入剖析算法的性能权衡
经验分享·笔记·算法·改行学it
逐步前行3 小时前
C数据结构--排序算法
c语言·数据结构·排序算法
王哈哈^_^3 小时前
【数据集+完整源码】水稻病害数据集,yolov8水稻病害检测数据集 6715 张,目标检测水稻识别算法实战训推教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
light_in_hand3 小时前
内存区域划分——垃圾回收
java·jvm·算法