forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountSetBits.java
66 lines (57 loc) · 1.74 KB
/
CountSetBits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.rampatra.bits;
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* User: rampatra
* Date: 4/4/15
* Time: 8:52 PM
* To change this template go to Preferences | IDE Settings | File and Code Templates
*/
public class CountSetBits {
/**
* Unoptimized version. Works for -ve numbers as well.
*
* @param number
* @return
*/
static int countSetBits(int number) {
int count = 0;
for (int i = 0; i < 32; i++) {
if ((number & 1) == 1) {
count++;
}
number = number >>> 1;
}
return count;
}
/**
* Optimized version. Works for -ve numbers as well.
* <p>
* Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset
* in each iteration. The time complexity is proportional to the number of bits set.
*
* @param n
* @return
* @link http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity
* @link http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive
*/
static int countSetBits(long n) {
int count = 0;
while (n != 0) {
n &= n - 1; // right most set bit in n is unset
count++;
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = Long.parseLong(in.nextLine());
System.out.println(countSetBits(n));
System.out.println(Integer.toBinaryString((int) -n));
System.out.println(countSetBits((int) -n));
}
}
/**
* Learn more:
* http://javarevisited.blogspot.in/2014/06/how-to-count-number-of-set-bits-or-1s.html
*/