{"record":{"id":"7ed57cfd7d9903ca","repo":"TheAlgorithms/Python","slug":"input-must-be-a-negative-integer","errorCode":null,"errorMessage":"input must be a negative integer","messagePattern":"input must be a negative integer","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"bit_manipulation/binary_twos_complement.py","lineNumber":25,"sourceCode":"    Return the two's complement representation of 'number'.\n\n    >>> twos_complement(0)\n    '0b0'\n    >>> twos_complement(-1)\n    '0b11'\n    >>> twos_complement(-5)\n    '0b1011'\n    >>> twos_complement(-17)\n    '0b101111'\n    >>> twos_complement(-207)\n    '0b100110001'\n    >>> twos_complement(1)\n    Traceback (most recent call last):\n        ...\n    ValueError: input must be a negative integer\n    \"\"\"\n    if number > 0:\n        raise ValueError(\"input must be a negative integer\")\n    binary_number_length = len(bin(number)[3:])\n    twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]\n    twos_complement_number = (\n        (\n            \"1\"\n            + \"0\" * (binary_number_length - len(twos_complement_number))\n            + twos_complement_number\n        )\n        if number < 0\n        else \"0\"\n    )\n    return \"0b\" + twos_complement_number\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()","sourceCodeStart":7,"sourceCodeEnd":43,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/bit_manipulation/binary_twos_complement.py#L7-L43","documentation":"Raised by twos_complement when number is positive. The function computes the two's-complement bit pattern of a negative integer; a positive input has no meaning for this operation, so it is rejected. Zero is accepted and returns '0b0' via the else branch.","triggerScenarios":"Calling twos_complement(1) or any positive integer. twos_complement(0) does not raise; only number > 0 triggers the error.","commonSituations":"Normalizing signs before encoding signed values (e.g., building fixed-width representations) and forgetting the positive branch; feeding magnitudes where signed negatives were expected.","solutions":["Ensure the value is negative: call twos_complement(-abs(number)) when you want the two's complement of a magnitude.","Branch at the call site: handle number >= 0 separately (e.g., plain bin(number)) and only route negatives to this function.","If you need arbitrary-width two's complement, format manually: format(number & (1 << width) - 1, f'0{width}b')."],"exampleFix":"# before\ntwos_complement(5)  # ValueError\n\n# after\nif number < 0:\n    result = twos_complement(number)\nelse:\n    result = '0b' + format(number, 'b')","handlingStrategy":"validation","validationCode":"if number > 0:\n    raise ValueError(\"twos_complement expects a negative integer\")","typeGuard":"def is_negative_int(n: object) -> bool:\n    return isinstance(n, int) and not isinstance(n, bool) and n < 0","tryCatchPattern":null,"preventionTips":["Branch on sign at the call site; route only negatives to twos_complement.","For fixed-width encodings use format(n & ((1 << w) - 1), f'0{w}b') which handles any sign.","Add unit tests covering 0 and positive inputs when wrapping this function."],"tags":["bit-manipulation","input-validation","python"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}