Skip to content

Commit 8d14b49

Browse files
Added CountBitsFlip algo (TheAlgorithms#6603)
* Added CountBitsFlip aldo * checkstyle fix * checkstyle fix --------- Co-authored-by: Alx <[email protected]>
1 parent 506b6d1 commit 8d14b49

File tree

2 files changed

+157
-0
lines changed

2 files changed

+157
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Implementation to count number of bits to be flipped to convert A to B
5+
*
6+
* Problem: Given two numbers A and B, count the number of bits needed to be
7+
* flipped to convert A to B.
8+
*
9+
* Example:
10+
* A = 10 (01010 in binary)
11+
* B = 20 (10100 in binary)
12+
* XOR = 30 (11110 in binary) - positions where bits differ
13+
* Answer: 4 bits need to be flipped
14+
*
15+
* Time Complexity: O(log n) - where n is the number of set bits
16+
* Space Complexity: O(1)
17+
*
18+
*@author [Yash Rajput](https://github.com/the-yash-rajput)
19+
*/
20+
public final class CountBitsFlip {
21+
22+
private CountBitsFlip() {
23+
throw new AssertionError("No instances.");
24+
}
25+
26+
/**
27+
* Counts the number of bits that need to be flipped to convert a to b
28+
*
29+
* Algorithm:
30+
* 1. XOR a and b to get positions where bits differ
31+
* 2. Count the number of set bits in the XOR result
32+
* 3. Use Brian Kernighan's algorithm: n & (n-1) removes rightmost set bit
33+
*
34+
* @param a the source number
35+
* @param b the target number
36+
* @return the number of bits to flip to convert A to B
37+
*/
38+
public static long countBitsFlip(long a, long b) {
39+
int count = 0;
40+
41+
// XOR gives us positions where bits differ
42+
long xorResult = a ^ b;
43+
44+
// Count set bits using Brian Kernighan's algorithm
45+
while (xorResult != 0) {
46+
xorResult = xorResult & (xorResult - 1); // Remove rightmost set bit
47+
count++;
48+
}
49+
50+
return count;
51+
}
52+
53+
/**
54+
* Alternative implementation using Long.bitCount().
55+
*
56+
* @param a the source number
57+
* @param b the target number
58+
* @return the number of bits to flip to convert a to b
59+
*/
60+
public static long countBitsFlipAlternative(long a, long b) {
61+
return Long.bitCount(a ^ b);
62+
}
63+
}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.Random;
6+
import org.junit.jupiter.api.DisplayName;
7+
import org.junit.jupiter.api.Test;
8+
9+
/**
10+
* Unit tests for CountBitsFlip.
11+
* Covers:
12+
* - simple examples
13+
* - zeros and identical values
14+
* - negative numbers and two's complement edge cases
15+
* - Long.MIN_VALUE / Long.MAX_VALUE
16+
* - randomized consistency checks between two implementations
17+
*/
18+
@DisplayName("CountBitsFlip Tests")
19+
class CountBitsFlipTest {
20+
21+
@Test
22+
@DisplayName("Example: A=10, B=20 => 4 bits")
23+
void exampleTenTwenty() {
24+
long a = 10L;
25+
long b = 20L;
26+
long expected = 4L;
27+
assertEquals(expected, CountBitsFlip.countBitsFlip(a, b), "Brian Kernighan implementation should return 4");
28+
assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b), "Long.bitCount implementation should return 4");
29+
}
30+
31+
@Test
32+
@DisplayName("Identical values => 0 bits")
33+
void identicalValues() {
34+
long a = 123456789L;
35+
long b = 123456789L;
36+
long expected = 0L;
37+
assertEquals(expected, CountBitsFlip.countBitsFlip(a, b));
38+
assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b));
39+
}
40+
41+
@Test
42+
@DisplayName("Both zeros => 0 bits")
43+
void bothZeros() {
44+
assertEquals(0L, CountBitsFlip.countBitsFlip(0L, 0L));
45+
assertEquals(0L, CountBitsFlip.countBitsFlipAlternative(0L, 0L));
46+
}
47+
48+
@Test
49+
@DisplayName("Small example: A=15 (1111), B=8 (1000) => 3 bits")
50+
void smallExample() {
51+
long a = 15L; // 1111
52+
long b = 8L; // 1000
53+
long expected = 3L; // differs in three low bits
54+
assertEquals(expected, CountBitsFlip.countBitsFlip(a, b));
55+
assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b));
56+
}
57+
58+
@Test
59+
@DisplayName("Negative values: -1 vs 0 => 64 bits (two's complement all ones)")
60+
void negativeVsZero() {
61+
long a = -1L;
62+
long b = 0L;
63+
long expected = 64L; // all 64 bits differ
64+
assertEquals(expected, CountBitsFlip.countBitsFlip(a, b));
65+
assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b));
66+
}
67+
68+
@Test
69+
@DisplayName("Long.MIN_VALUE vs Long.MAX_VALUE => 64 bits")
70+
void minMaxLongs() {
71+
long a = Long.MIN_VALUE;
72+
long b = Long.MAX_VALUE;
73+
long expected = 64L; // MAX ^ MIN yields all ones on 64-bit long
74+
assertEquals(expected, CountBitsFlip.countBitsFlip(a, b));
75+
assertEquals(expected, CountBitsFlip.countBitsFlipAlternative(a, b));
76+
}
77+
78+
@Test
79+
@DisplayName("Randomized consistency: both implementations agree across many pairs")
80+
void randomizedConsistency() {
81+
final int iterations = 1000;
82+
final Random rnd = new Random(12345L); // deterministic seed for reproducibility
83+
84+
for (int i = 0; i < iterations; i++) {
85+
long a = rnd.nextLong();
86+
long b = rnd.nextLong();
87+
88+
long res1 = CountBitsFlip.countBitsFlip(a, b);
89+
long res2 = CountBitsFlip.countBitsFlipAlternative(a, b);
90+
91+
assertEquals(res2, res1, () -> String.format("Mismatch for a=%d, b=%d: impl1=%d, impl2=%d", a, b, res1, res2));
92+
}
93+
}
94+
}

0 commit comments

Comments
 (0)