- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# Count numbers whose difference with N is equal to XOR with N in C++

We are a number N. The goal is to find numbers between 0 and N whose difference with N is equal to XOR with N.

We will do this by traversing no. from i=0 to i<=N and for each i, if (N-X==i^N) then increment count.

Let us understand with examples.

**Input** − X=6

**Output** − Count of numbers whose difference with N == XOR with N: 4

**Explanation** − Numbers are 0 2 4 6.

**Input** − X=20

**Output** − Count of numbers whose difference with N == XOR with N: 4

**Explanation** − Numbers are 0 4 16 20

## Approach used in the below program is as follows

We take integer N.

Function diffisXOR(int n) takes n and returns a count of numbers whose difference with n is equal to xor with n.

Take the initial count as 0.

Traverse from i=0 to i<=n.

If i-n==i^n. Increment count

At the end of for loop count will have the desired result.

Return count and print.

## Example

#include <bits/stdc++.h> #include <math.h> using namespace std; int diffisXOR(int n){ int count = 0; for (int i = 0; i <= x; i++){ if((x-i)==(i^x)) { count++; } } return count; } int main(){ int N = 15; int nums=diffisXOR(N); cout <<endl<<"Count of numbers whose difference with N == XOR with N: "<<nums; return 0; }

## Output

If we run the above code it will generate the following output −

Count of numbers whose difference with N == XOR with N: 16

- Related Articles
- Count numbers whose XOR with N is equal to OR with N in C++
- Count smaller numbers whose XOR with n produces greater value in C++
- Count numbers whose sum with x is equal to XOR with x in C++
- Count numbers < = N whose difference with the count of primes upto them is > = K in C++
- Count numbers (smaller than or equal to N) with given digit sum in C++
- C++ code to find composite numbers whose difference is n
- Find N distinct numbers whose bitwise Or is equal to K in C++
- Count smaller values whose XOR with x is greater than x in C++
- Find a Number X whose sum with its digits is equal to N in C++
- Find N distinct numbers whose bitwise Or is equal to K in Python
- Maximum Primes whose sum is equal to given N in C++
- Minimum numbers which is smaller than or equal to N and with sum S in C++
- Count pairs with Odd XOR in C++
- Maximum XOR using K numbers from 1 to n in C++
- Count of n digit numbers whose sum of digits equals to given sum in C++