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;
}
相关推荐
情缘晓梦.4 小时前
C语言分支与循环
c语言·开发语言
山楂树の5 小时前
买卖股票的最佳时机(动态规划)
算法·动态规划
AAA.建材批发刘哥5 小时前
03--C++ 类和对象中篇
linux·c语言·开发语言·c++·经验分享
小O的算法实验室5 小时前
2024年IEEE TMC SCI1区TOP,面向无人机辅助 MEC 系统的轨迹规划与任务卸载的双蚁群算法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
无才顽石6 小时前
什么是数学
算法·数理象
AlexMercer10126 小时前
【操作系统】操作系统期末考试 简答题 焚决
c语言·经验分享·笔记·操作系统
CoderCodingNo6 小时前
【GESP】C++五级真题(数论, 贪心思想考点) luogu-B4070 [GESP202412 五级] 奇妙数字
开发语言·c++·算法
百***58846 小时前
MATLAB高效算法实战技术文章大纲1
人工智能·算法·matlab
学嵌入式的六子6 小时前
如何使用VScode开发STM32【喂饭级教程】-全过程讲解
c语言·ide·vscode·stm32·单片机·嵌入式硬件
墨辰JC6 小时前
C语言可变参数讲解:stdarg.h应用
c语言·开发语言·蓝桥杯·内存·蓝桥杯嵌入式