#202
Easy Algorithms Happy number
Hash Table Math Two Pointers
59.3% acceptance
Jan 12, 2026
11844
1635
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn is_happy(n: i32) -> bool {
let mut slow = n;
let mut fast = n;
loop {
slow = Self::get_next(slow);
fast = Self::get_next(Self::get_next(fast));
if fast == 1 { return true; }
if slow == fast { return false; }
}
}
fn get_next(mut n: i32) -> i32 {
let mut sum = 0;
while n > 0 {
let digit = n % 10;
sum += digit * digit;
n /= 10;
}
sum
}
}