-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0306_additive_number.rs
More file actions
45 lines (41 loc) · 1.2 KB
/
s0306_additive_number.rs
File metadata and controls
45 lines (41 loc) · 1.2 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
#![allow(unused)]
pub struct Solution {}
impl Solution {
pub fn is_additive_number(num: String) -> bool {
for i in 1..num.len() - 1 {
if i > 1 && &num[0..1] == "0" {
continue;
}
for j in i + 1..num.len() {
if j - i > 1 && &num[i..i + 1] == "0" {
continue;
}
let mut n1 = (&num[0..i]).parse::<u64>().unwrap();
let mut n2 = (&num[i..j]).parse::<u64>().unwrap();
let mut s = (&num[0..j]).to_string();
loop {
let n3 = n1 + n2;
n1 = n2;
n2 = n3;
s += n3.to_string().as_str();
if s == num {
return true;
}
if !num.starts_with(&s) {
break;
}
}
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_306() {
assert_eq!(Solution::is_additive_number("112358".to_string()), true);
assert_eq!(Solution::is_additive_number("199100199".to_string()), true);
}
}