zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    进程间通迅之消息队列
    进程间通讯之共享内存
    标准块CP功能实现
    标准字符cp功能
    文件cp功能
    jest 的 coverage 提示 unknown 的解决方案
    js中的相等
    getBoundingClientRect 和 requestAnimFrame 的polyfill
    设计模式(4): 给组件实现单独的store
    Vue项目移动端滚动穿透问题
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15416424.html
Copyright © 2011-2022 走看看