classSolution: defbaseNeg2(self, n: int) -> str: if n == 0or n == 1: returnstr(n) res = [] while n: remainder = n & 1 res.append(str(remainder)) n -= remainder n //= -2 return''.join(res[::-1])
数学
1 2 3 4 5 6 7 8 9 10
classSolution: defbaseNeg2(self, n: int) -> str: val = 0x55555555 ^ (0x55555555 - n) if val == 0: return"0" res = [] while val: res.append(str(val & 1)) val >>= 1 return''.join(res[::-1])