📌  相关文章
📜  二进制表示形式的0和1的XOR计数

📅  最后修改于: 2021-05-07 09:49:15             🧑  作者: Mango

给定一个数字,任务是在给定数字的二进制表示中找到计数为0和计数为1的XOR。
例子:

Input  : 5
Output : 3
Binary representation : 101
Count of 0s = 1, 
Count of 1s = 2
1 XOR 2 = 3.

Input  : 7
Output : 3
Binary representation : 111
Count of 0s = 0
Count of 1s = 3
0 XOR 3 = 3.

这个想法很简单,我们遍历一个数字的所有位,计数0和1,最后返回两个计数的XOR。

C++
// C++ program to find XOR of counts 0s and 1s in
// binary representation of n.
#include
using namespace std;
 
// Returns XOR of counts 0s and 1s in
// binary representation of n.
int countXOR(int n)
{
    int count0 = 0, count1 = 0;
    while (n)
    {
        //calculating count of zeros and ones
        (n % 2 == 0) ? count0++ :count1++;
        n /= 2;
    }
    return (count0 ^ count1);
}
 
// Driver Program
int main()
{
    int n = 31;
    cout << countXOR (n);
    return 0;
}


Java
// Java program to find XOR of counts 0s
// and 1s in binary representation of n.
 
class GFG {
     
    // Returns XOR of counts 0s and 1s
    // in binary representation of n.
    static int countXOR(int n)
    {
        int count0 = 0, count1 = 0;
        while (n != 0)
        {
            //calculating count of zeros and ones
            if(n % 2 == 0)
            count0++ ;
            else
            count1++;
            n /= 2;
        }
        return (count0 ^ count1);
    }
     
    // Driver Program
    public static void main(String[] args)
    {
        int n = 31;
        System.out.println(countXOR (n));
    }
}
 
// This code is contributed by prerna saini


Python3
# Python3 program to find XOR of counts 0s
# and 1s in binary representation of n.
 
# Returns XOR of counts 0s and 1s
# in binary representation of n.
def countXOR(n):
     
    count0, count1 = 0, 0
    while (n != 0):
     
        # calculating count of zeros and ones
        if(n % 2 == 0):
            count0 += 1
        else:
            count1 += 1
        n //= 2
         
    return (count0 ^ count1)
     
# Driver Code
n = 31
print(countXOR(n))
 
# This code is contributed by Anant Agarwal.


C#
// C# program to find XOR of counts 0s
// and 1s in binary representation of n.
using System;
 
class GFG {
      
    // Returns XOR of counts 0s and 1s
    // in binary representation of n.
    static int countXOR(int n)
    {
        int count0 = 0, count1 = 0;
        while (n != 0)
        {
             
            // calculating count of zeros
            // and ones
            if(n % 2 == 0)
                count0++ ;
            else
                count1++;
                 
            n /= 2;
        }
         
        return (count0 ^ count1);
    }
      
    // Driver Program
    public static void Main()
    {
         
        int n = 31;
         
        Console.WriteLine(countXOR (n));
    }
}
 
// This code is contributed by Anant Agarwal.


PHP


Javascript


输出:

5

一个观察结果是,对于2 ^ x – 1形式的数,输出始终为x。我们可以通过首先检查n + 1是否为2的幂来直接产生这种情况的答案。