-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.rs
51 lines (45 loc) · 1.15 KB
/
main.rs
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
fn main() {
for i in 0..20 {
let x = Solution::is_happy(i);
println!("i = {:#?}, x = {:#?}", i, x);
}
}
struct Solution {}
impl Solution {
pub fn is_happy(n: i32) -> bool {
let mut slow = Self::square_sum(n);
let mut fast = Self::square_sum(slow);
loop {
if fast == 1 { return true }
if slow == fast { return false }
slow = Self::square_sum(slow);
fast = Self::square_sum(fast);
fast = Self::square_sum(fast);
}
}
pub fn square_sum(mut n: i32) -> i32 {
let mut sum = 0;
while n > 0 {
let digit = n % 10;
sum += digit.pow(2);
n /= 10;
}
println!("n = {:#?}, sum = {:#?}", n, sum);
sum
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::is_happy(19), true);
}
#[test]
fn square_sum() {
assert_eq!(Solution::square_sum(19), 82);
assert_eq!(Solution::square_sum(82), 68);
assert_eq!(Solution::square_sum(68), 100);
assert_eq!(Solution::square_sum(100), 1);
}
}