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
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
这道题定义了一种快乐数,就是说对于某一个正整数,如果对其各个位上的数字分别平方,然后再加起来得到一个新的数字,再进行同样的操作,如果最终结果变成了1,则说明是快乐数,如果一直循环但不是1的话,就不是快乐数。
解法1:可以发现,任意一个大于1的数执行上述循环过程若干次后,都会得到一个小于等于10的数。因此我们先算出[0,10]之间哪些是快乐数并保存下来,然后对输入数字不断进行上述过程循环,直至小于等于10,再判断即可。
class Solution { public: bool isHappy(int n) { vector<bool> yes = {false, true, false, false, false, false, false, true, false, false, true}; while(n > 10) { int num = 0; string s = to_string(n); for(int i = 0; i < s.size(); ++i) num += (int)pow(s[i] - '0', 2); n = num; } return yes[n]; } };
解法2:根据定义,一个数经过上述循环过程,要么得到1退出,要么无限循环下去。可以发现,无限循环下去的情况会是在若干次循环过程中,某两次得到了不为1的相同数字。因此可以将循环过程中得到的数字存下来,再下一次循环后得到的数字与前面的进行比较,若出现过则终止循环并与1进行比较。
class Solution { public: bool isHappy(int n) { unordered_map<int, int> m; while(n != 1) { int num = 0; string s = to_string(n); for(int i = 0; i < s.size(); ++i) num += (int)pow(s[i] - '0', 2); n = num; if(m.find(n) != m.end()) break; else ++m[n]; } return n == 1; } };