Skip to content

Commit

Permalink
Added Count Bit to Flip
Browse files Browse the repository at this point in the history
  • Loading branch information
Ansh-Vikalp committed Oct 18, 2024
1 parent 5b47395 commit 1eff632
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Beginner Level πŸ“/Count Bits To Flip/BitFlipCount.java
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();
}

}
36 changes: 36 additions & 0 deletions Beginner Level πŸ“/Count Bits To Flip/question.md
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`

0 comments on commit 1eff632

Please sign in to comment.