Easy to understand solution,4ms in c++


  • 0
    V
    class Solution {
    public:
        bool isHappy(int n) {
            int sum = 0, num = 0;
            set<int> s;
            s.insert(n);
            
            while (1)
            {
                sum = 0;
                while (n > 0)
                {
                    num = n % 10;
                    sum += num * num;
                    n /= 10;
                }
                if (sum == 1) return true;
                else 
                    n = sum;
                if (s.find(n) != s.end())
                    return false;
                else 
                    s.insert(n);
            }
        }
    };

  • 0

    Thx for sharing!

    The code is pretty neat while it may not suit for whiteboard interview I think? (cause we cant get intermediate answers).


  • 0
    V

    yeah,it doesn't suit for whiteboard interview,and I think the interviewer won't ask this type of question or he just want to know how you think and how you handle the loop


  • 0

    I think I have answered the wrong question which is about getting the maximum number 810 (by 9910). Sorry for that.


Log in to reply
 

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