avatar
Siz Long

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 me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

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 me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

1017. Negative binary conversion

  2024-01-01        
字数统计: 133字   |   阅读时长: 1min

topic:

1017. Negative binary conversion

Thought:

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
class Solution:
def baseNeg2(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
impl Solution {
pub fn base_neg2(mut n: i32) -> String {
let mut 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()
}
}
  • Python
  • answer

扫一扫,分享到微信

微信分享二维码
994.Rotten orange
1017.Negative binary conversion
目录
  1. 1. topic:
  2. 2. Thought:
  3. 3. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号