- Related Questions & Answers
- Python program to count total set bits in all number from 1 to n.
- Count total number of digits from 1 to N in C++
- Number of 1 Bits in Python
- Count number of 1s in the array after N moves in C
- Count digits in given number N which divide N in C++
- Count unset bits of a number in C++
- Find smallest number n such that n XOR n+1 equals to given k in C++
- Minimum number using set bits of a given number in C++
- Count n digit numbers divisible by given number in C++
- Queries to count the number of unordered co-prime pairs from 1 to N in C++
- Count number of step required to reduce N to 1 by following certain rule in C++
- C# program to count total bits in a number
- Count pieces of the circle after N cuts in C++
- Count number of solutions of x^2 = 1 (mod p) in given range in C++
- Count total bits in a number in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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

Input− num = 10Output− 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 = 5Output− 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

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.

#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; }

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

count is: 1

Advertisements