|
| 1 | +package me.ramswaroop.bits; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by IntelliJ IDEA. |
| 5 | + * |
| 6 | + * @author: ramswaroop |
| 7 | + * @date: 6/3/15 |
| 8 | + * @time: 3:50 PM |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * PARITY: Parity of a number refers to whether it |
| 13 | + * contains an odd or even number of 1-bits. The number |
| 14 | + * has “odd parity”, if it contains odd number of 1-bits |
| 15 | + * and is “even parity” if it contains even number of 1-bits. |
| 16 | + */ |
| 17 | +public class Parity { |
| 18 | + |
| 19 | + /** |
| 20 | + * Uses BRIAN KERNIGAN'S bit counting. The time complexity is |
| 21 | + * proportional to the number of bits set. |
| 22 | + * {@see http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity} |
| 23 | + * |
| 24 | + * @param n |
| 25 | + * @return |
| 26 | + */ |
| 27 | + public static boolean isEvenParity(long n) { |
| 28 | + boolean parity = true; |
| 29 | + |
| 30 | + while (n > 0) { |
| 31 | + parity = !parity; |
| 32 | + n = n & (n - 1); |
| 33 | + } |
| 34 | + return parity; |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | + /** |
| 39 | + * Old school method |
| 40 | + * |
| 41 | + * @param n |
| 42 | + * @return true if {@param n} has even number of 1-bits |
| 43 | + */ |
| 44 | + public static boolean isEvenParityByCountingSetBits(long n) { |
| 45 | + int setBitsCount = 0; |
| 46 | + |
| 47 | + while (n > 0) { |
| 48 | + if ((n & 1) == 1) setBitsCount++; |
| 49 | + n >>= 1; |
| 50 | + } |
| 51 | + |
| 52 | + return setBitsCount % 2 == 0; |
| 53 | + } |
| 54 | + |
| 55 | + public static void main(String a[]) { |
| 56 | + System.out.println(isEvenParity(0)); |
| 57 | + System.out.println(isEvenParity(1)); |
| 58 | + System.out.println(isEvenParity(5)); |
| 59 | + System.out.println(isEvenParity(6)); |
| 60 | + System.out.println(isEvenParity(7)); |
| 61 | + System.out.println(isEvenParity(12)); |
| 62 | + System.out.println("=========================="); |
| 63 | + System.out.println(isEvenParityByCountingSetBits(0)); |
| 64 | + System.out.println(isEvenParityByCountingSetBits(1)); |
| 65 | + System.out.println(isEvenParityByCountingSetBits(5)); |
| 66 | + System.out.println(isEvenParityByCountingSetBits(6)); |
| 67 | + System.out.println(isEvenParityByCountingSetBits(7)); |
| 68 | + System.out.println(isEvenParityByCountingSetBits(12)); |
| 69 | + } |
| 70 | +} |
0 commit comments