{"record":{"id":"46bd6c163f5b42e7","repo":"TheAlgorithms/Java","slug":"input-must-be-non-negative","errorCode":null,"errorMessage":"Input must be non-negative","messagePattern":"Input must be non-negative","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java","lineNumber":25,"sourceCode":" * @author navadeep\n */\npublic final class CountSetBits {\n\n    private CountSetBits() {\n        // Utility class, prevent instantiation\n    }\n\n    /**\n     * Counts total number of set bits in all numbers from 1 to n\n     * Time Complexity: O(log n)\n     *\n     * @param n the upper limit (inclusive)\n     * @return total count of set bits from 1 to n\n     * @throws IllegalArgumentException if n is negative\n     */\n    public static int countSetBits(int n) {\n        if (n < 0) {\n            throw new IllegalArgumentException(\"Input must be non-negative\");\n        }\n\n        if (n == 0) {\n            return 0;\n        }\n\n        // Find the largest power of 2 <= n\n        int x = largestPowerOf2InNumber(n);\n\n        // Total bits at position x: x * 2^(x-1)\n        int bitsAtPositionX = x * (1 << (x - 1));\n\n        // Remaining numbers after 2^x\n        int remainingNumbers = n - (1 << x) + 1;\n\n        // Recursively count for the rest\n        int rest = countSetBits(n - (1 << x));\n","sourceCodeStart":7,"sourceCodeEnd":43,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java#L7-L43","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nCountSetBits.countSetBits(len - offset);  // throws if offset > len\n\n// after\nint n = Math.max(0, len - offset);\nCountSetBits.countSetBits(n);","handlingStrategy":"validation","validationCode":"if (n < 0) throw new IllegalArgumentException(\"n must be >= 0\");\nCountSetBits.countSetBits(n);","typeGuard":"public static boolean isNonNegative(int n) {\n    return n >= 0;\n}","tryCatchPattern":"try {\n    return CountSetBits.countSetBits(n);\n} catch (IllegalArgumentException e) {\n    return 0;\n}","preventionTips":["Clamp n to 0 if it can underflow.","Validate signed input before counting.","Guard upstream subtractions that produce n."],"tags":["bit-manipulation","count-bits","argument-validation","illegalargumentexception"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}