feat: 1017_convert_to_base_negative_2
This commit is contained in:
parent
758200be5c
commit
cbde308101
7
1017_convert_to_base_negative_2/Cargo.lock
generated
Normal file
7
1017_convert_to_base_negative_2/Cargo.lock
generated
Normal 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"
|
6
1017_convert_to_base_negative_2/Cargo.toml
Normal file
6
1017_convert_to_base_negative_2/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "convert_to_base_negative_2"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
27
1017_convert_to_base_negative_2/src/lib.rs
Normal file
27
1017_convert_to_base_negative_2/src/lib.rs
Normal 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()
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user