位运算

来源:互联网 发布:c#和java工资相差多少 编辑:程序博客网 时间:2024/05/29 10:36

位运算

  • 位运算
    • 2的幂
    • 二进制数中1的数量
    • 倒转比特


2的幂

Given an integer, write a function to determine if it is a power of two.

/* C */bool isPowerOfTwo(int n) {    return (n & n-1) == 0 && n > 0;}

Power of Two


二进制数中1的数量

For example
32位的11: 00000000000000000000000000001011
return 3

// C++class Solution {public:    int hammingWeight(uint32_t n) {        n = n - ((n >> 1) & 0x55555555);          n = (n & 0x33333333) + ((n >> 2) & 0x33333333);          n = (n + (n >> 4)) & 0xf0f0f0f;          n = n + (n >> 8);          n = n + (n >> 16);          return n & 0x3f;    }};

大致的想法就是错位相加,如1111,
先把偶数位上的数加到奇数位上来:1111+(1111>>1) = 1110;
留下奇数位:1110 & 0x5 = 0100;
正好是十进制4,1111正好有4个1
Number of 1 Bits


倒转比特

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

# Ruby# @param {Integer} n, a positive integer# @return {Integer}def reverse_bits(n)    sprintf("%.32b", n).reverse.to_i(2)end

位运算的题还是得用c语言做才有意思:

/* C */uint32_t reverseBits(uint32_t n) {    int i = 0, t[32] = {0};    uint32_t sum = 0;    while(n){        t[i++] = n & 1;        n >>= 1;    }    for(i = 0;i < 32; i++){        sum += t[i] << 31 - i ;    }    return sum;}

Reverse Bits

0 0