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;
}
相关推荐
音视频牛哥12 分钟前
鸿蒙 NEXT RTSP/RTMP 播放器如何回调 RGB 数据并实现 AI 视觉算法分析
人工智能·算法·harmonyos·鸿蒙rtmp播放器·鸿蒙rtsp播放器·鸿蒙next rtsp播放器·鸿蒙next rtmp播放器
飞Link15 分钟前
掌控 Agent 的时空法则:LangGraph Checkpoint (检查点) 机制深度实战
开发语言·python·算法
乐迪信息21 分钟前
智慧港口中AI防爆摄像机的船舶越线识别功能
大数据·人工智能·物联网·算法·目标跟踪
m0_7167652328 分钟前
数据结构--单链表的插入、删除、查找详解
c语言·开发语言·数据结构·c++·笔记·学习·visual studio
F_D_Z29 分钟前
扩散模型快速采样:从渐进蒸馏到并行推理
人工智能·算法·加速采样
睡一觉就好了。1 小时前
哈希表(一)
算法·散列表
輕華1 小时前
Word2Vec与CBOW算法实战:从词向量到上下文感知
人工智能·算法·word2vec
Matlab程序猿小助手1 小时前
【MATLAB源码-第315期】基于matlab的䲟鱼优化算法(ROA)无人机三维路径规划,输出做短路径图和适应度曲线.
开发语言·算法·matlab
圣保罗的大教堂1 小时前
leetcode 874. 模拟行走机器人 中等
leetcode
itman3011 小时前
C语言printf输出格式:%d %f %s等用法详解
c语言·字符串·printf·格式化输出·整数