题目:
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: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
完成一个算法检测一个数字是否是“happy”的。快乐数(happy number)有以下的特性:在给定的进位制下,该数字所有数位(digits)的平方和,得到的新数再次求所有数位的平方和,如此重复进行,最终结果必为1。
思路一:转载地址:https://leetcode.com/discuss/89535/0ms-solution-beats-97-perhaps-the-most-easy-one-to-understand
利用map保存原数以及后面所产生的所有位元素平方和,当新产生的平方和数等于1或者产生与原数相等的数,则循环结束。
代码:8ms
class Solution { public: bool isHappy(int n) { int num = 0; unordered_map<int, bool> table; //保存平方和数 table[n] = 1; //将原数保存进map中 while(n!=1){ while(n){ //计算新生成的平方和 num += (n%10) * (n%10); n /= 10; } if(table[num]){ //判断新生成的平方和在map中是否有保存,有则退出,说明有循环产生 break; }else{ table[num] = 1; //无循环产生,将平方和保存进map中,进行下一次循环。 n = num; num = 0; } } return 1==n; } };思路二:
定义两个步长slow和fast,slow每次执行一次操作,fast每次执行两次操作,不管是最后等于1,还是产生循环均会产生slow==fast,故停止条件即为slow==fast;
代码:4ms
class Solution { public: bool isHappy(int n) { int slow, fast; slow = fast = n; do{ slow = compute(slow); fast = compute(fast); fast = compute(fast); }while(slow!=fast); return 1==slow; } private: int compute(int n){ int num = 0; while(n){ num += (n%10) * (n%10); n /= 10; } return num; } };思路三:
快乐数每次都会回到1,而不快乐数每次会产生循环,并且循环都会回到4中。
代码:0ms
class Solution { public: bool isHappy(int n){ int num = 0; while(n!=1 && n!=4){ while(n){ num += (n%10) * (n%10); n /= 10; } n = num; num = 0; } return 1==n; } };