We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 5eadbad commit f34d01dCopy full SHA for f34d01d
src/bin/integer-replacement.rs
@@ -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