• C++关于二进制位操作小结


    #include <iostream>
    using namespace std;
    //二进制位逆序。
    int Grial(int x)
    {
        int n = 32;
        int count = 0;
        while (n--)
        {
            count|= ((x&0x1) << n);
            x = ((unsigned)x >> 1);
        }
        return count;
    }
    int main()
    {
        cout << Grial(1) << endl;
        return 0;
    }
    
    
    #include <iostream>
    using namespace std;
    //二进制位中的奇偶位互换。
    int Grial(int x)
    {
        int sum1 = x & 0x55555555;
        int sum2 = x & 0xaaaaaaaa;
        sum1 <<= 1;
        sum2 >>= 1;
        return sum1 | sum2;
    }
    int main()
    {
        cout << Grial(6) << endl;
        return 0;
    }
    
    
    #include <iostream>
    using namespace std;
    //求两个数的和。

    int Grial(int x, int y) { if (!y)return x; //int ret = x^y; //-1%2=-1; int sum = x^y; int num = ((x&y)<<1); return Grial(sum,num); } int main() { cout << Grial(3, 5) << endl; return 0; } #include <iostream> using namespace std; //推断一个数是不是2的n次方。 bool Grial(int x) { return (x&(x - 1)) == 0; } int main() { cout << Grial(4) << endl; return 0; } #include <iostream> using namespace std; //求二进制中1的个数。 int Grial(int x) { int count = 0; while (x) { x = x&(x - 1); count++; } return count; } int main() { cout << Grial(15) << endl; } #include <iostream> using namespace std; //求平均值。 int Grial(int x,int y) { return (x&y) + ((x^y) >> 1); } int main() { cout << Grial(20, 48) << endl; return 0; } #include <iostream> using namespace std; //求平均值。 int Grial(int x,int y) { return x - (x - y) / 2; } int main() { cout << Grial(3,9) << endl; return 0; }

  • 相关阅读:
    济南学习 Day5 T3 晚
    Codevs 1043 ==洛谷 P1004 方格取数
    济南学习 Day 5 T2 晚
    济南学习 Day 5 T1 晚
    济南学习 Day 5 T3 am
    济南学习 Day 5 T2 am
    LeetCode Weekly Contest 8
    poj-1410 Intersection
    leetcode-Warm Up Contest-Aug.21
    poj-1384 Piggy-Bank
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7048146.html
Copyright © 2020-2023  润新知