DEV Community

shine
shine

Posted on

[📝LeetCode #202] Happy Number

🎀 The Problem

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.

Example:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

👩‍💻 My Answer

class Solution {
    public boolean isHappy(int n) {
        Set set = new HashSet();

        while (true) {
            int sum = 0;

            while (n != 0) {
                sum += (n % 10) * (n % 10);
                n = n / 10;
            }

            if (sum == 1)
                return true;

            if (!set.contains(sum))
                set.add(sum);
            else if (set.contains(sum))
                return false;

            n = sum;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

Pro & Con

  • 🔺 Runtime & Memory
  • ✖️ Nested Loop (two while loops)

💋 Ideal Answer

Approach - "Fast and Slow Pointers"

When I was solving this, I could not come up with a HashSet system because I was not aware that the same remainder may come up (infinite cycle). Since my initial attempt was not working, I watched the YouTube video:
Nikhil Lohia's Happy Number (LeetCode 202)

BUT, the method introduced in Nikhil Lohia's video was not BEATING 100%. So, I watched the new video:
AlgoMasterIO's Happy Number (LeetCode 202)

This video introduced the two pointers: fast and slow. This algorithm is also used for the linked list problem but we can use this for the Happy Number problem.

New Code

class Solution {
    public boolean isHappy(int n) {

        int s = n,f = n; // slow , fast

        do{
            s = compute(s); // slow computes only once
            f = compute(compute(f)); // fast computes 2 times

            if(s == 1)return true; // if we found 1 then happy indeed !!!
        }while(s != f); // else at some point they will meet in the cycle

        return false;
    }

    private int compute (int n) {
        int sum = 0;

        while (n != 0) {
            sum += (n % 10) * (n % 10);
            n = n / 10;
        }
        return sum;
    }
}
Enter fullscreen mode Exit fullscreen mode

💡 What I Learned

  • Java does not use ^ for power calculation. Instead of 10^2,
    10*10

  • How to use fast and slow pointer

  • how to use do while instead of while

do {
CODE
} while (CONDITION)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)