c++ 0ms O(1) space


  • 0
    D

    Firstly, I calculate the result of number 1 - 9 by hand, find that only 1 and 7 is happy number, so the solution is very simple:

    code :
    class Solution {
    public:
    bool isHappy(int n) {
    int num;
    int t;
    while (n >= 10)
    {
    num = 0;
    while (n)
    {
    t = n % 10;
    num += t * t;
    n /= 10;
    }
    n = num;
    }
    return n == 1 || n == 7;
    }
    };


Log in to reply
 

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