My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.
The difference from binary is just not always//2,It’s every number//-1
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defbaseNeg2(self, n: int) -> str: k = 1 ans = [] while n: if n % 2: ans.append('1') n -= k else: ans.append('0') n //= 2 k *= -1 return''.join(ans[::-1]) or'0'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
implSolution { pubfnbase_neg2(mut n: i32) ->String { letmut ans = Vec::new(); while n != 0 { if n % 2 != 0 { ans.push('1'); n = (n - 1) / -2; } else { ans.push('0'); n /= -2; } } if ans.is_empty() { ans.push('0'); } ans.reverse(); ans.iter().collect() } }