My solution using recursion in C++ 6ms


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

  • 0
    Y
    This post is deleted!

  • 0
    Y

    Can you explain why SumValue(n) < 10 and SumValue(n) != 1, then the return value is false? Thanks!


  • 0
    Y

    This is due to the definition of the happy number, if SumValue(n) < 10 and SumValue(n) != 1, the process of calculation will loop endlessly. Hope this can answer your question.


  • 0
    L
    This post is deleted!

  • 3
    L

    How about isHappy(1111111)?

    sumValue(1111111) = 7, and the program will enter the if statement.

    But 7 != 1, hence your program will return false.

    Actually, 1111111->7->49->97->130->10->1 is a happy number.

    Therefore, I think this solution is wrong.


Log in to reply
 

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