Skip to content

Commit 134985e

Browse files
committed
Bit Difference using C++
1 parent 49d70c3 commit 134985e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Bit Manipulation/Bit_Difference.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
/*
3+
You are given two numbers A and B. The task is to count the number of bits needed to be flipped to convert A to B.
4+
5+
Example 1:
6+
7+
Input: A = 10, B = 20
8+
Output: 4
9+
Explanation:
10+
A = 01010
11+
B = 10100
12+
As we can see, the bits of A that need
13+
to be flipped are 01010. If we flip
14+
these bits, we get 10100, which is B.*/
15+
//Initial Template for C++
16+
17+
#include<bits/stdc++.h>
18+
using namespace std;
19+
20+
// Function to find number of bits to be flip
21+
// to convert A to B
22+
int countBitsFlip(int a, int b){
23+
24+
// Your logic here
25+
int ans=a^b;
26+
int c=0;
27+
while(ans>0)
28+
{
29+
ans &=(ans-1);
30+
c++;
31+
}
32+
return c;
33+
34+
}
35+
36+
// { Driver Code Starts.
37+
38+
// Driver Code
39+
int main()
40+
{
41+
int t;
42+
cin>>t;// input the testcases
43+
while(t--) //while testcases exist
44+
{
45+
int a,b;
46+
cin>>a>>b; //input a and b
47+
48+
cout<<countBitsFlip(a, b)<<endl;
49+
}
50+
return 0;
51+
} // } Driver Code Ends

0 commit comments

Comments
 (0)