feat: 1017_convert_to_base_negative_2

This commit is contained in:
SquidSpirit 2025-08-20 23:44:47 +08:00
parent 758200be5c
commit cbde308101
3 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "convert_to_base_negative_2"
version = "0.1.0"

View File

@ -0,0 +1,6 @@
[package]
name = "convert_to_base_negative_2"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@ -0,0 +1,27 @@
pub struct Solution;
impl Solution {
pub fn base_neg2(mut n: i32) -> String {
let mut rems: Vec<char> = vec![];
loop {
let mut r = n % -2;
n /= -2;
// n * Q + r = n * (Q + x) + (r - n)
// => x = 1
if r < 0 {
r += 2;
n += 1;
}
rems.push(if r == 0 { '0' } else { '1' });
if n == 0 {
break;
}
}
rems.iter().rev().collect()
}
}