File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments