</>

202. Happy Number

Easy NeetCode 150
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Math & Geometry
Time
—
Space
—

Standard Solution (C++)

SummaryGiven a positive integer, repeatedly replace it with the sum of squares of its digits; determine whether this process eventually reaches 1 (happy) or loops forever without reaching it (not happy).

Approach
  • Use Floyd's cycle detection (slow/fast pointers) to detect whether the sequence converges to 1 or enters a cycle.
  • The "next" helper computes the sum of squares of each digit.
  • If the fast pointer ever hits 1, the number is happy. If slow and fast meet at any other value, a cycle exists and the number is not happy.
  • This runs in O(log n) per step and uses O(1) space — no hash set needed.
#include <cstddef>
using namespace std;

class Solution {
    // Compute the sum of squares of digits of n.
    int next(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;
            sum += d * d;
            n /= 10;
        }
        return sum;
    }

public:
    bool isHappy(int n) {
        // Floyd's cycle detection: slow moves one step, fast moves two.
        int slow = n, fast = next(n);
        while (fast != 1 && slow != fast) {
            slow = next(slow);
            fast = next(next(fast));
        }
        // If fast reached 1, the sequence converges — happy number.
        return fast == 1;
    }
};
Time O(log n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    bool isHappy(int n) {
        // loop this:
        // 1. extract each digits
        // 2. get the sum
        // 3. check if the sum==1

        // 2^31 -> 1000^3 -> 1e9 (approx)
        // use 10 digit to be upper bound
        // max: 9^2 * 10 = 810 -> max loop number
        // the other methods are to use hash set or two pointer

        for(int i=0; i<810; ++i){
            int sum=0;
            while(n!=0){
                int digit=n%10;
                n/=10;
                sum+=(digit*digit);
            }
            if(sum==1){
                return true;
            }
            n=sum;
        }

        return false;
    }
};

// Time: O(1)
// Space: O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern