DDSA
Advertisement

202. Happy Number

Time: O(log n)
Space: O(1)

Approach

Floyd’s cycle detection on the digit-square-sum sequence (slow/fast pointers); the number is happy if the cycle ends at 1.

202.cs
C#
// Approach: Floyd’s cycle detection on the digit-square-sum sequence
// (slow/fast pointers); the number is happy if the cycle ends at 1.
// Time: O(log n) Space: O(1)

public class Solution
{
    public bool IsHappy(int n)
    {
        int slow = SquaredSum(n);
        int fast = SquaredSum(SquaredSum(n));

        while (slow != fast)
        {
            slow = SquaredSum(slow);
            fast = SquaredSum(SquaredSum(fast));
        }

        return slow == 1;
    }

    private int SquaredSum(int n)
    {
        int sum = 0;
        while (n > 0)
        {
            sum += (int)Math.Pow(n % 10, 2);
            n /= 10;
        }
        return sum;
    }
}

Advertisement
Was this solution helpful?