Count number of bits changed after adding 1 to given N
Last Updated :
28 Apr, 2021
Given an integer . The task is to find the number of bits changed after adding 1 to the given number.
Examples:
Input : N = 5
Output : 2
After adding 1 to 5 it becomes 6.
Binary representation of 5 is 101.
Binary representation of 6 is 110.
So, no. of bits changed is 2.
Input : N = 1
Output : 2
There are three approaches to find the number of changed bits in the result obtained after adding 1 to the given value N:
- Approach 1: Add 1 to given integer and compare the bits of N and the result obtained after addition and count the number of unmatched bit.
- Approach 2: In case if 1 is added to N, then the total number of bits changed is defined by the position of 1st Zero from right i.e. LSB as zero. In this case, 1 is added to 1 then it got changed and passes a carry 1 to its next bit but if 1 is added to 0 only 0 changes to 1 and no further carry is passed.
- Approach 3: For finding a number of changed bits when 1 is added to a given number take XOR of n and n+1 and calculate the number of set bits in the resultant XOR value.
Below is the implementation of the Approach 3:
C++
#include <bits/stdc++.h>
using namespace std;
int findChangedBit( int n)
{
int XOR = n ^ (n + 1);
int result = __builtin_popcount(XOR);
return result;
}
int main()
{
int n = 6;
cout << findChangedBit(n) << endl;
n = 7;
cout << findChangedBit(n);
return 0;
}
|
Java
class GFG
{
static int findChangedBit( int n)
{
int XOR = n ^ (n + 1 );
int result = Integer.bitCount(XOR);
return result;
}
public static void main(String[] args)
{
int n = 6 ;
System.out.println(findChangedBit(n));
n = 7 ;
System.out.println(findChangedBit(n));
}
}
|
Python3
def findChangedBit(n):
XOR = n ^ (n + 1 )
result = bin (XOR).count( "1" )
return result
if __name__ = = '__main__' :
n = 6
print (findChangedBit(n))
n = 7
print (findChangedBit(n))
|
C#
using System;
class GFG
{
static int findChangedBit( int n)
{
int XOR = n ^ (n + 1);
int result = bitCount(XOR);
return result;
}
static int bitCount( int x)
{
int setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
public static void Main(String[] args)
{
int n = 6;
Console.WriteLine(findChangedBit(n));
n = 7;
Console.WriteLine(findChangedBit(n));
}
}
|
Javascript
<script>
function findChangedBit(n)
{
let XOR = n ^ (n + 1);
let result = bitCount(XOR);
return result;
}
function bitCount(x)
{
let setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
let n = 6;
document.write(findChangedBit(n) + "<br>" );
n = 7;
document.write(findChangedBit(n));
</script>
|
Share your thoughts in the comments
Please Login to comment...