Bit Manipulation Gray Code Sequence (Java)
Generate a Gray code sequence of n bits in Java using bit manipulation where consecutive values differ by one bit.
Code
import java.util.*;
public class GrayCode {
public static List<Integer> generate(int n) {
int count = 1 << n;
List<Integer> result = new ArrayList<>(count);
for (int i = 0; i < count; i++) result.add(i ^ (i >>> 1));
return result;
}
public static int popcount(int x) { x = x - ((x >>> 1) & 0x55555555); x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); x = (x + (x >>> 4)) & 0x0f0f0f0f; return (x * 0x01010101) >>> 24; }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.