[Python] python infinite precision

Discussão em 'Python' iniciado por Stack, Junho 23, 2025.

  1. Stack

    Stack Membro Participativo

    Can anyone explain the last part of the following code to check for overflow?

    The code is the solution for LeetCode question 137. Single Number II.

    I know it might be overflowing due to the MSB is set.

    Base on the problem statement, the number must be in - 2^31 ~ 2^31-1. We can use deduction to correct the overflow.

    But can we use mask i.e. 0x7FFF FFFF FFFF FFFF to solve that?

    I think it is No.

    Since the precision is infinite in Python, the mask method would not work. Is that correct?

    class Solution:
    def singleNumber(self, nums: List[int]) -> int:

    # Loner.
    loner = 0

    # Iterate over all bits
    for shift in range(32):
    bit_sum = 0

    # For this bit, iterate over all integers
    for num in nums:

    # Compute the bit of num, and add it to bit_sum
    bit_sum += (num >> shift) & 1

    # Compute the bit of loner and place it
    loner_bit = bit_sum % 3
    loner = loner | (loner_bit << shift)

    # Do not mistaken sign bit for MSB.
    if loner >= (1 << 31):
    loner = loner - (1 << 32)

    return loner

    Continue reading...

Compartilhe esta Página