190. Reverse Bits

复制代码
/**
190. Reverse Bits
https://leetcode.com/problems/reverse-bits/
Reverse bits of a given 32 bits unsigned integer.
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.
*/
pub struct Solution {}

impl Solution {
    /*
    Solution: scan n from right to left, if current bit is one, left shift and plus one; just left shift if zero;
    Time:O(32), Space:O(1);
    */
    pub fn reverse_bits(x: u32) -> u32 {
        let (mut result, mut x) = (0u32, x);
        for _ in 0..32 {
            if ((x & 1) == 1) {
                result <<= result + 1;
            } else {
                result <<= 1;
            }
            x >>= 1;
        }
        return result;
    }
}
复制代码

 

posted @   johnny_zhao  阅读(40)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-10-17 186. Reverse Words in a String II
2020-10-17 151. Reverse Words in a String
2020-10-17 345. Reverse Vowels of a String
点击右上角即可分享
微信分享提示