n&(n-1)的妙用 (转)
今天无聊拿起《编程之美》看了下,发现原来n&(n-1)还有很多妙用。原理:n与n-1的区别在于,对于n,从右向左数的第一个"1"开始一直到右,和n-1,完全相反
n&(n-1)作用:将n的二进制表示中的最低位为1的改为0,先看一个简单的例子:
n = 10100(二进制),则(n-1) = 10011 ==》n&(n-1) = 10000
可以看到原本最低位为1的那位变为0。
弄明白了n&(n-1)的作用,那它有哪些应用?
1. 求某一个数的二进制表示中1的个数
while (n >0 ) {
count ++;
n &= (n-1);
}
2. 判断一个数是否是2的方幂
n > 0 && ((n & (n - 1)) == 0 )
如果A&B==0,表示A与B的二进制形式没有在同一个位置都为1的时候。
不妨先看下n-1是什么意思。
令:n=1101011000(二进制,十进制也一样),则
n-1=1101010111。
n&(n-1)=1101010000
由此可以得出,n和n-1的低位不一样,直到有个转折点,就是借位的那个点,从这个点开始的高位,n和n-1都一样,如果高位一样这就造成一个问题,就是n和n-1在相同的位上可能会有同一个1,从而使((n & (n-1)) != 0),如果想要
((n & (n-1)) == 0),则高位必须全为0,这样就没有相同的1。
所以n是2的幂或0
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.
class Solution
{
public:
int hammingWeight(uint32_t n)
{
int count=0;
while(n)
{
n=n&(n-1);
count++;
}
return count;
}
};
2.Power of Two
Given an integer, write a function to determine if it is a power of two.
class Solution {
public:
bool isPowerOfTwo(int n)
{
return n > 0 && !(n & (n - 1));
}
};
3.Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
我们这里先考虑一般的二叉树(BT),然后再考虑这个二叉树是二叉搜索树(BST)的情况。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p -> val < root -> val && q -> val < root -> val)
return lowestCommonAncestor(root -> left, p, q);
if (p -> val > root -> val && q -> val > root -> val)
return lowestCommonAncestor(root -> right, p, q);
return root;
}
};