首页 > 其他 > 详细

位运算问题

时间:2015-11-24 12:56:16      阅读:375      评论:0      收藏:0      [点我收藏+]

n & (n - 1)的作用:把n中为1的最低位变为0.

Power of Two

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

解法:2的次幂的特征是有且仅有一位为1,其余为均为零。故可利用判断n & (n - 1)是否为零来判断n是否为2的次幂。

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return (n > 0) && ((n & (n - 1)) == 0);
    }
}

Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.

解法:根据n & (n - 1)的执行次数判断1的个数,直到为0.

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int result = 0;
        while (n != 0) {
            result++;
            n &= (n - 1);
        }
        return result;
    }
}

还有一种解法:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int result = 0;
        while (n != 0) {
            result += n & 1;
            n >>>= 1;
        }
        return result;
    }
}

Bitwise AND of Numbers Range

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

本题的目标是把m和n从最高位开始连续相同的位数不变,第一位不相同的位数开始都变为0.

解法一:找出低位中的1,将1置0.

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        while (n > m) {
            n &= (n - 1);
        }
        return n;
    }
}

解法二:迭代依次将低位置0.

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        if (m == n) {
            return m;
        }
        if (m == n - 1) {
            return m & n;
        }
        return rangeBitwiseAnd(m / 2, n / 2) << 1;
    }
}

 

位运算问题

原文:http://www.cnblogs.com/shinning/p/4991191.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!