I solved LeetCode 137 in C++. TLDR of the problem: array of numbers, nums
is given; all numbers appear 3 times, except one which appear only once. Find the number that appears once.
When trying to convert my C++ solution to python, I came across few funny things, i.e. the bit operations seem to behave a bit differently in python, on negative integers.
So, I switched to using formatting as binary string - but, to my surprise, INT_MIN (-2^32 - 1) resulted in a string of length 33, containing the sign as well. Where could I read more about this and understand why it happens?
How can I improve the code below, to make it more pythonic?
def singleNumber(self, nums: List[int]) -> int:
INT_BASE = 33 # because of INT32_MIN
# give python what it likes
counts_nz = [0 for _ in range(INT_BASE)]
vals_bit = ["0" for _ in range(INT_BASE)]
for num in nums:
# 33 because of INT32_MIN takes 33 bits to represent.
for idx, bin_val in enumerate(f"{num:033b}"):
if bin_val != "0": # can be "1" or "-"
counts_nz[idx] += 1
vals_bit[idx] = bin_val
# make the bits binary string -- set to value for M3 + 1 and 0 otherwise
bin_res = "".join(
[
vals_bit[idx] if count % 3 == 1 else "0"
for idx, count in enumerate(counts_nz)
]
)
return int(bin_res, 2)
[0] * INT_BASE
and['0'] * INT_BASE
\$\endgroup\$