-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathstunning-numbers.rs
More file actions
104 lines (91 loc) · 2.98 KB
/
stunning-numbers.rs
File metadata and controls
104 lines (91 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::collections::HashMap;
use std::io;
fn is_strobogrammatic(number: &str) -> bool {
let flip_map: HashMap<char, char> = [
('0', '0'), ('1', '1'), ('2', '2'), ('5', '5'),
('6', '9'), ('8', '8'), ('9', '6')
].iter().cloned().collect();
let n = number.len();
let chars: Vec<char> = number.chars().collect();
for i in 0..=(n/2) {
let c = chars[i];
if !flip_map.contains_key(&c) ||
chars[n - i - 1] != *flip_map.get(&c).unwrap() {
return false;
}
}
true
}
fn reverse_number(number: &str, is_odd: bool) -> String {
let flip_map: HashMap<char, char> = [
('0', '0'), ('1', '1'), ('2', '2'), ('5', '5'),
('6', '9'), ('8', '8'), ('9', '6')
].iter().cloned().collect();
let mut result: Vec<char> = number.chars().collect();
let reversed: String = if is_odd {
number[..number.len()-1].chars()
.rev()
.map(|c| flip_map[&c])
.collect()
} else {
number.chars()
.rev()
.map(|c| flip_map[&c])
.collect()
};
result.extend(reversed.chars());
result.iter().collect()
}
fn next_strobogrammatic(number: &str) -> String {
let current = if is_strobogrammatic(number) {
println!("true");
(number.parse::<i64>().unwrap() + 1).to_string()
} else {
println!("false");
number.to_string()
};
let valid_digits = "0125689";
let n = current.len();
let mut is_odd = n % 2 == 1;
let mut prefix = current[..(n + 1) / 2].to_string();
loop {
let mut i = 0;
while i < prefix.len() {
if valid_digits.contains(prefix.chars().nth(i).unwrap()) {
i += 1;
} else {
let zeros = prefix.len() - i - 1;
let prefix_part = &prefix[..=i];
let incremented = prefix_part.parse::<i64>().unwrap() + 1;
if incremented.to_string().len() > prefix_part.len() {
is_odd = !is_odd;
}
prefix = format!("{}{}", incremented, "0".repeat(zeros));
i = 0;
}
}
let result = reverse_number(&prefix, is_odd);
if is_strobogrammatic(&result) &&
result.parse::<i64>().unwrap() > current.parse::<i64>().unwrap() {
return result;
}
let incremented = prefix.parse::<i64>().unwrap() + 1;
if incremented.to_string().len() > prefix.len() {
if is_odd {
prefix = incremented.to_string();
prefix.pop();
} else {
prefix = incremented.to_string();
}
is_odd = !is_odd;
} else {
prefix = incremented.to_string();
}
}
}
fn main() {
let mut input_line = String::new();
io::stdin().read_line(&mut input_line).unwrap();
let n = input_line.trim_matches('\n').to_string();
println!("{}", next_strobogrammatic(&n));
}