C++ simple recursion solution


  • 0
    M

    Among the integer less than 10, only 1 and 7 are happy number.

        bool isHappy(int n) {
            if (n == 1 || n == 7) return true;
            if (n < 10) return false;
            int sum = 0;
            while (n) {
                sum += (n % 10) * (n % 10);
                n /= 10;
            }
            return isHappy(sum);
        }

  • 0

    how can you confirm that between 1-10 except 1 and 7,others will return false?


  • 0
    M

    @gragon
    This can be confirmed by deduction. Take 7 as an example:
    7 -> 49 -> 16 + 81 = 97 -> 81 + 49 = 130 -> 1 + 9 + 0 = 10 -> 1


Log in to reply
 

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