# Count number of bits changed after adding 1 to given N in C++

C++Server Side ProgrammingProgramming

We are given a number let’s say num and the task is to calculate the total number of bits changed when 1 is added to a number.

Binary representation of a number is done by converting the given number into the form of 0’s and 1’s and it is done by various methods. In one method, we calculate the LCM of a given number by 2 and if a reminder is other than 0 then the bit is set to 1 else it will be set to 0.

## Addition table for bits are

0 + 1 = 1
1 + 0 = 1
0 + 0 = 0
1 + 1 = 1 ( 1 bit carry)

## For Example

Input − num = 10
Output − count is : 1

Explanation − binary representation of 10 is 1010 and when 1 is added to it representation becomes 1011. Clearly only one bit got changed therefore the count is 1.

Input − num = 5
Output − count is : 2

Explanation − binary representation of 5 is 101 and when 1 is added to it representation becomes 110. Clearly two bits got changed therefore the count is 2

## Approach used in the below program is as follows

• Input the number of type integer let’s say, int num

• Declare a variable that will store the count let’s say, int count

• Take another variable let’s say temp that will calculate the XOR of num and set it to n ^ (n + 1)

• In the count variable call __builtin_popcount(temp). This function is to calculate the count of numbers in a given integer binary representation. It is an inbuilt function of GCC compiler.

• Return the count

• Print the result.

## Example

Live Demo

#include <iostream>
using namespace std;
// Function to find number of changed bit
int changedbit(int n){
int XOR = n ^ (n + 1);
// Count set bits in xor value
int count = __builtin_popcount(XOR);
return count;
}
int main(){
int n = 10;
cout <<"count is: " <<changedbit(n);
return 0;
}

## Output

If we run the above code we will get the following output −

count is: 1
Updated on 15-May-2020 12:52:46