算法设计与应用基础-第九周&第十周

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

1.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.

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)的情况。

查找两个node的最早的公共祖先,分三种情况:
1. 如果两个node在root的两边,那么最早的公共祖先就是root。
2. 如果两个node在root的左边,那么把root.leftChild作为root,再递归。
3. 如果两个node在root的右边,那么把root.rightChild作为root,再递归。
/**
 * 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;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值