LeetCode/solutions/202. Happy Number.md

29 lines
748 B
Markdown
Raw Normal View History

2018-09-13 04:37:33 +00:00
# [202. Happy Number](https://leetcode.com/problems/happy-number/description/)
# 思路
按照题目的意思进行循环判断每次循环结果是否为1若是则返回true否则用map记录结果然后修改n进行下一次循环。
# C++
2019-09-13 15:08:41 +00:00
``` C++
2018-09-13 04:37:33 +00:00
class Solution {
private:
int count_sum(int n){ // 定义题目中所述的求和函数
int sum = 0;
while(n > 0){
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
public:
bool isHappy(int n) {
map<int, int>mp;
while(n){
if(n == 1) return true;
if(mp[n] == 1) return false;
mp[n] = 1;
n = count_sum(n);
}
return false;
}
};
```