zoukankan      html  css  js  c++  java
  • n&(n-1)

    1. 判断一个正整数是否为2的乘方数

        数据对比(uint_16 n;)

    -------------------------------------------------------------------------------------------------

    n         n 的二进制表示           (n - 1)    (n-1) 的二进制表示        n&(n - 1)

    -------------------------------------------------------------------------------------------------

    2       0000000000000010b    1        0000000000000001b    0000000000000000b

    -------------------------------------------------------------------------------------------------

    4       0000000000000100b    3        0000000000000011b    0000000000000000b

    -------------------------------------------------------------------------------------------------

    16     0000000000010000b    15      0000000000001111b     0000000000000000b

    -------------------------------------------------------------------------------------------------

    100   0000000001100100b    99      0000000001100011b     0000000001100000b

    -------------------------------------------------------------------------------------------------

    128   0000000010000000b    127    0000000001111111b      0000000000000000b

    -------------------------------------------------------------------------------------------------

     unsigned char isPower(unsigned int n)

    {
        return(((n == 0)  || (n & (n-1))) ? 0x00 : 0x01);
    }

    2. 判断一个正整数转化为二进制后数字 “1” 的个数

    unsigned char NumOfOne(unsigned int n)
    {
        unsigned char i = 0;
        while(n)
        {
            n &= n-1;
            i++;
        }
        return i;
    }
  • 相关阅读:
    用python对汉诺塔动态的实现
    用python语言算π值并且带有进度条
    turtle库的学习笔记
    Leetcode 230 二叉搜索树中第k小的元素
    Leetcode 665 非递减数列
    Leetcode 1423 可获得的最大点数
    Leetcode 222 完全二叉树的节点个数
    Leetcode 1208尽可能使字符串相等
    Leetcode 199 二叉树的右视图
    Leetcode 634 子数组最大平均数
  • 原文地址:https://www.cnblogs.com/Waming-zhen/p/6283358.html
Copyright © 2011-2022 走看看