Skip to content

Commit f34d01d

Browse files
committed
src/bin/integer-replacement.rs
1 parent 5eadbad commit f34d01d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/bin/integer-replacement.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
fn main() {
2+
println!("{}", Solution::integer_replacement(2147483647));
3+
}
4+
5+
struct Solution;
6+
7+
impl Solution {
8+
pub fn integer_replacement(n: i32) -> i32 {
9+
let mut h = std::collections::HashMap::new();
10+
Self::f(n as i64, &mut h) as i32
11+
}
12+
13+
fn f(n: i64, h: &mut std::collections::HashMap<i64, i64>) -> i64 {
14+
if n == 1 {
15+
return 0;
16+
}
17+
18+
if let Some(x) = h.get(&n) {
19+
return *x;
20+
}
21+
22+
let m = if n % 2 == 0 {
23+
Self::f(n / 2, h) + 1
24+
} else {
25+
Self::f(n - 1, h).min(Self::f(n + 1, h)) + 1
26+
};
27+
28+
h.insert(n, m);
29+
m
30+
}
31+
}

0 commit comments

Comments
 (0)