TheAlgorithms/Java · error · IllegalArgumentException
Input must be non-negative
Error message
Input must be non-negative
What it means
Thrown by CountSetBits.countSetBits(n) when n is negative. The method counts set bits across all integers from 1 to n using a logarithmic formula based on the largest power of two <= n; that formula only holds for non-negative n. Negative inputs are rejected rather than producing wrong results.
Source
Thrown at src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java:25
* @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));
View on GitHub (pinned to fdfb9a395b)
Solutions
- Ensure n >= 0 before calling; n == 0 is valid and yields 0.
- Clamp n to 0 if a non-negative fallback is acceptable, or reject negative input upstream.
- Check the computation that produced n for underflow.
Example fix
// before CountSetBits.countSetBits(len - offset); // throws if offset > len // after int n = Math.max(0, len - offset); CountSetBits.countSetBits(n);
Defensive patterns
Strategy: validation
Validate before calling
if (n < 0) throw new IllegalArgumentException("n must be >= 0");
CountSetBits.countSetBits(n); Type guard
public static boolean isNonNegative(int n) {
return n >= 0;
} Try / catch
try {
return CountSetBits.countSetBits(n);
} catch (IllegalArgumentException e) {
return 0;
} Prevention
- Clamp n to 0 if it can underflow.
- Validate signed input before counting.
- Guard upstream subtractions that produce n.
When it happens
Trigger: Calling `countSetBits(-1)` or `countSetBits(-100)`. The guard `n < 0` triggers; n == 0 returns 0 (valid), and any positive n is processed. The largestPowerOf2InNumber helper is only invoked for n > 0.
Common situations: n derived from a subtraction that underflows; n read from signed input that can be negative; off-by-one where n represents a size passed as size-1 that went negative.
Related errors
- Invalid BCD digit: {}
- Shift amount cannot be negative: {}
- Bit positions must be between 0 and 31
- Alpha must be between 0 and 1.
- order must be greater than zero
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/46bd6c163f5b42e7.
Report an issue: GitHub.