-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5b47395
commit 1eff632
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import java.util.Scanner; | ||
|
||
public class BitFlipCount { | ||
|
||
// Method to count the number of bits to flip to convert 'a' to 'b' | ||
public static int countBitsToFlip(int a, int b) { | ||
// XOR of a and b gives the positions where the bits differ | ||
int xor = a ^ b; | ||
int count = 0; // Initialize a counter to count differing bits | ||
|
||
// Loop until all differing bits are cleared | ||
while (xor != 0) { | ||
// This operation clears the rightmost set bit in xor | ||
xor = xor & (xor - 1); | ||
count++; // Increment the count for each set bit | ||
} | ||
|
||
return count; // Return the total number of bits to flip | ||
} | ||
|
||
public static void main(String[] args) { | ||
Scanner sc = new Scanner(System.in); | ||
int a = sc.nextInt(); | ||
int b = sc.nextInt(); | ||
|
||
// Output the number of bits to flip to convert 'a' to 'b' | ||
System.out.println("Bits to flip: " + countBitsToFlip(a, b)); | ||
|
||
sc.close(); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
## Problem Statement | ||
Write a Java program to find the number of bits that need to be flipped to convert one number `A` to another number `B`. | ||
|
||
### Input | ||
- Two integers `A` and `B` where `0 <= A, B <= 10^9`. | ||
|
||
### Output | ||
- An integer representing the number of bits that need to be flipped to convert `A` to `B`. | ||
|
||
### Example | ||
|
||
#### Example 1: | ||
**Input**: | ||
`A = 29, B = 15` | ||
|
||
**Output**: | ||
`2` | ||
|
||
**Explanation**: | ||
Binary representation of `29` is `11101` and binary representation of `15` is `01111`. | ||
Two bits differ at positions 3 and 4 (0-based index). | ||
|
||
|
||
#### Example 2: | ||
**Input**: | ||
`A = 10, B = 20` | ||
|
||
**Output**: | ||
`4` | ||
|
||
**Explanation**: | ||
Binary representation of `10` is `1010` and binary representation of `20` is `10100`. | ||
Four bits need to be flipped. | ||
|
||
### Constraints | ||
- `0 <= A, B <= 10^9` |