Leetcode 202.快乐数

题目描述

编写一个算法来判断一个数是不是“快乐数”。

一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例:

1
2
输入: 19  
输出: true

解释:

$1^2 + 9^2 = 82$
$8^2 + 2^2 = 68$
$6^2 + 8^2 = 100$
$1^2 + 0^2 + 0^2 = 1$

题目分析

就求呗…
把每次的结果存在哈希堆里来查重

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int toNextInt(int x) {
int digits = log10(x)+1;
int res = 0;
while(x != 0) {
res += (x%10) * (x%10);
x /= 10;
}
return res;
}

class Solution {
public:
unordered_set<int> nums;
bool isHappy(int n) {
int res = n;
while(res != 1) {
if(nums.find(res) == nums.end()) {
nums.insert(res);
res = toNextInt(res);
}else {
return false;
}
}
return true;
}
};
0%