大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/happy-number/description/
内容
Write an algorithm to determine if a number n 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.
- 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.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input: n = 2
Output: false
Constraints:
- 1 <= n <= 231 - 1
解题
这题要求Happy Number。它符合一种规律:迭代计算10进制数字每位平方的和,最终得到数字1。如果不是Happy Numer,那么计算过程中一定会出现某种循环。这样我们可以通过set结构来做校验。
#include <set>
using namespace std;class Solution {
public:bool isHappy(int n) {set<int> s;while (n != 1) {if (s.find(n) != s.end()) {return false;}s.insert(n);int sum = 0;for (int c = n % 10; n != 0; n /= 10, c = n % 10) {sum += c * c;}n = sum;}return true;}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/202-Happy-Number/cplusplus