-
Notifications
You must be signed in to change notification settings - Fork 354
/
Copy pathBit_Difference.cpp
51 lines (41 loc) · 887 Bytes
/
Bit_Difference.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
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.
Example 1:
Input: A = 10, B = 20
Output: 4
Explanation:
A = 01010
B = 10100
As we can see, the bits of A that need
to be flipped are 01010. If we flip
these bits, we get 10100, which is B.*/
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
// Function to find number of bits to be flip
// to convert A to B
int countBitsFlip(int a, int b){
// Your logic here
int ans=a^b;
int c=0;
while(ans>0)
{
ans &=(ans-1);
c++;
}
return c;
}
// { Driver Code Starts.
// Driver Code
int main()
{
int t;
cin>>t;// input the testcases
while(t--) //while testcases exist
{
int a,b;
cin>>a>>b; //input a and b
cout<<countBitsFlip(a, b)<<endl;
}
return 0;
} // } Driver Code Ends