• Reverse Bits


    Reverse Bits

    问题:

    Reverse bits of a given 32 bits unsigned integer.

    For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

    他人代码:

    public class Solution {
        public int reverseBits(int n) {
            int rst = 0;
            for(int i = 0 ; i < 32; i++)
            {
                if( (n&(0x00000001<<i)) !=0)
                    rst |= (0x80000000 >>> i);
            }
            return rst;
        }
    }
    View Code

    学习之处:

    • 所谓bitvector是指一个32位的数组,可以通过循环,对于某一个数字,判断移动1个位置到32个位置为止,每一位的情况。
    • <<左移相当于乘以2,左移补0 >>相当于除以2,对于正数补0,对于负数补1
    • >>>也是左移,相当于除以2,对于正数还是负数都是补0,所以>>>适用于无符号的数
    • & 与运算 | 或运算,为了保险起见,所有的位运算都加上()
    • 对于一个数的二进制形式的操作,考虑使用bitvector的方法
  • 相关阅读:
    hdu-1114
    hdu2546
    POJ-3126
    POJ-1915
    ZOJ-1709
    Codeforces 847H
    Codeforces 847C
    Codeforces 847I
    Codeforces 847E
    算法笔记--矩阵及矩阵快速幂
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4337592.html
Copyright © 2020-2023  润新知