0 ms C++ solution, straight and easy to understand


  • -1
    L
    class Solution {
    public:
        bool isHappy(int n) {
            if(n == 1)
                return true;
            int result = 0;
            while(1)
            {
                while(n < 10)
                    n = n * n;
                while(n > 0)
                {
                    result += (n%10) * (n%10);
                    n = (n - n%10) / 10;
                }
                if(result == 1)
                    return true;
                else if(result < 10)
                    return false;
                else
                {
                    n = result;
                    result = 0;
                }
            }
        }
    };

  • 0
    A

    Doubt on the correctness. Why return false if (result < 10)? How do you know the loop will finally terminate?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.