TheAlgorithms/Python · error · ValueError

Input must be a non-negative integer

Error message

Input must be a non-negative integer

What it means

Raised by get_index_of_rightmost_set_bit when the input is not an int or is negative. The function isolates the lowest set bit with number & ~(number - 1) and shifts to find its index — integer-only logic — so both wrong types and negatives raise this single ValueError.

Source

Thrown at bit_manipulation/index_of_rightmost_set_bit.py:33

    2
    >>> get_index_of_rightmost_set_bit(8)
    3
    >>> get_index_of_rightmost_set_bit(-18)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    >>> get_index_of_rightmost_set_bit('test')
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    >>> get_index_of_rightmost_set_bit(1.25)
    Traceback (most recent call last):
        ...
    ValueError: Input must be a non-negative integer
    """

    if not isinstance(number, int) or number < 0:
        raise ValueError("Input must be a non-negative integer")

    intermediate = number & ~(number - 1)
    index = 0
    while intermediate:
        intermediate >>= 1
        index += 1
    return index - 1


if __name__ == "__main__":
    """
    Finding the index of rightmost set bit has some very peculiar use-cases,
    especially in finding missing or/and repeating numbers in a list of
    positive integers.
    """
    import doctest

    doctest.testmod(verbose=True)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert numeric inputs: get_index_of_rightmost_set_bit(int(value)).
  2. Handle 0 explicitly before calling, since the function returns -1 rather than raising for it.
  3. For positive ints, an O(1) alternative is (number & -number).bit_length() - 1.

Example fix

# before
get_index_of_rightmost_set_bit('test')  # ValueError

# after
get_index_of_rightmost_set_bit(int('40'))  # 3
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(number, int) or number < 0:
    raise ValueError("need a non-negative int")
if number == 0:
    raise ValueError("0 has no set bit (function would return -1)")

Type guard

def is_positive_int(n: object) -> bool:
    return isinstance(n, int) and not isinstance(n, bool) and n > 0

Prevention

When it happens

Trigger: Calling get_index_of_rightmost_set_bit('test'), get_index_of_rightmost_set_bit(1.25), or (-4). Note: input 0 is accepted but returns -1 because no bit is set.

Common situations: Feeding bitmask indices from string configs or float computations; passing 0 and misreading the -1 return as an index instead of handling it.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/c3930383e9521414. Report an issue: GitHub.