当前位置:网站首页>[LeetCode]202. Happy Number(平衡二叉树 哈希表)

[LeetCode]202. Happy Number(平衡二叉树 哈希表)

2021-07-20 03:51:26 李响Superb

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1


      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

思路1:

写一个方法计算平方和
定义两个数slow, fast来记录前后两次得到的平方和
如果前后两个数字相等,进入死循环,这是就需要跳出循环
判断slow是否为1,是的话返回true,否则返回false
思路2:

本来我以为不用哈希表就是最快的解法了,但是天外有人
刚开始我没看懂,就拿之前写的算法测试了1-9这些数字,发现只有1和7返回true,并且不管循环多少次平方和最终还是要小于10的
于是就有了下面的解法

bool isHappy(int n) {//0ms
        if(n == 0) return 0;
        int squares = n;
        while(squares >= 10){
            int temp = 0;
            while(squares) {
                temp += (squares%10)*(squares%10);
                squares = squares/10;
            }
            squares = temp;
        }

        if(squares == 1 || squares == 7)
            return true;
        else
            return false;
    }

      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

版权声明
本文为[李响Superb]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_14013325/2891921