202. Happy Number

Link

Solution

The most critical question is how to find an infinite loop?

We can use the slow and fast pointer to find if it existed.

    public boolean isHappy(int n) {
        if(n == 1) return true;
        int fast = n, slow = n;
        
        do{
            slow = calculate(slow);
            fast = calculate(fast);
            fast = calculate(fast);
            if(fast == 1) return true;
        }while(fast != slow);
        return false; //contain loop
    }
    
    public int calculate(int n){
        int next = 0;
        while(n != 0){
            
            next += (n % 10) * (n % 10);
            n = n / 10;
        }

        return next;
    }

Last updated

Was this helpful?