forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSetBits.java
More file actions
79 lines (67 loc) · 2.07 KB
/
CountSetBits.java
File metadata and controls
79 lines (67 loc) · 2.07 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.thealgorithms.bitmanipulation;
/**
* Utility class to count total set bits from 1 to N
* A set bit is a bit in binary representation that is 1
*
* @author navadeep
*/
public final class CountSetBits {
private CountSetBits() {
// Utility class, prevent instantiation
}
/**
* Counts total number of set bits in all numbers from 1 to n
* Time Complexity: O(log n)
*
* @param n the upper limit (inclusive)
* @return total count of set bits from 1 to n
* @throws IllegalArgumentException if n is negative
*/
public static int countSetBits(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input must be non-negative");
}
if (n == 0) {
return 0;
}
// Find the largest power of 2 <= n
int x = largestPowerOf2InNumber(n);
// Total bits at position x: x * 2^(x-1)
int bitsAtPositionX = x * (1 << (x - 1));
// Remaining numbers after 2^x
int remainingNumbers = n - (1 << x) + 1;
// Recursively count for the rest
int rest = countSetBits(n - (1 << x));
return bitsAtPositionX + remainingNumbers + rest;
}
/**
* Finds the position of the most significant bit in n
*
* @param n the number
* @return position of MSB (0-indexed from right)
*/
private static int largestPowerOf2InNumber(int n) {
int position = 0;
while ((1 << position) <= n) {
position++;
}
return position - 1;
}
/**
* Alternative naive approach - counts set bits by iterating through all numbers
* Time Complexity: O(n log n)
*
* @param n the upper limit (inclusive)
* @return total count of set bits from 1 to n
*/
public static int countSetBitsNaive(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input must be non-negative");
}
int count = 0;
for (int i = 1; i <= n; i++) {
count += Integer.bitCount(i);
}
return count;
}
}