Algo-Sim › Math & Geometry

Happy Number

Easy · Math & Geometry · step through it in Java, Python and C++ on your own input

Repeatedly sum the squares of the digits; detect the loop with Floyd’s slow and fast pointers, using O(1) memory instead of a set.

Problem

A number is happy if repeatedly replacing it by the sum of the squares of its digits eventually reaches 1. Otherwise the process loops forever in a cycle that does not include 1. Return true if n is happy.

Constraints

Edge cases to test

Follow-up questions

Why must it end in a cycle or at 1?
After one step any number below 10¹⁰ becomes at most 810, so the sequence lives in a finite set and must repeat.
Set or Floyd’s cycle detection?
A set is simpler but uses memory; Floyd’s slow and fast pointers use O(1) space with the same O(log n) steps per move.

Solution

Java

public boolean isHappy(int n) {
    int slow = n, fast = next(n);
    while (fast != 1 && slow != fast) {
        slow = next(slow);
        fast = next(next(fast));
    }
    return fast == 1;
}

private int next(int n) {
    int sum = 0;
    while (n > 0) {
        int d = n % 10;
        sum += d * d;
        n /= 10;
    }
    return sum;
}

Python

def is_happy(n):
    slow, fast = n, next_number(n)
    while fast != 1 and slow != fast:
        slow = next_number(slow)
        fast = next_number(next_number(fast))
    return fast == 1


def next_number(n):
    total = 0
    while n > 0:
        n, d = divmod(n, 10)
        total += d * d
    return total

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isHappy(int n) {
        int slow = n, fast = next(n);
        while (fast != 1 && slow != fast) {
            slow = next(slow);
            fast = next(next(fast));
        }
        return fast == 1;
    }

    int next(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;
            sum += d * d;
            n /= 10;
        }
        return sum;
    }
};

More Math & Geometry problems