Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e448255

Browse files
author
Ram swaroop
committed
count set bits from -n to n : done
1 parent a4a2242 commit e448255

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package me.ramswaroop.bits;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 7/22/15
8+
* @time: 12:42 PM
9+
*/
10+
public class CountSetBitsFromMinusNtoN {
11+
12+
/**
13+
* Explanation:
14+
*
15+
* -3: 101
16+
* -2: 110
17+
* -1: 111
18+
* 0: 000
19+
* 1: 001
20+
* 2: 010
21+
* 3: 110
22+
*
23+
* If you fold the above representation between -1 and 0, the total no. of set bits from -3 to 2
24+
* will be equal to the total no. of bits in nos. from -3 to 2.
25+
*
26+
* @param n
27+
* @return
28+
*/
29+
public static int countSetBitsFromMinusNtoN(int n) {
30+
return n * 32 + CountSetBits.countSetBits((long) n); // 32 because int is of 32 bits in java
31+
}
32+
33+
public static void main(String a[]) {
34+
System.out.println(countSetBitsFromMinusNtoN(3));
35+
System.out.println(countSetBitsFromMinusNtoN(0));
36+
System.out.println(countSetBitsFromMinusNtoN(9));
37+
}
38+
}

0 commit comments

Comments
 (0)