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
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; } };
677

被折叠的 条评论
为什么被折叠?



