LeetCode/solutions/202. Happy Number.md
2019-09-13 23:08:41 +08:00

29 lines
748 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [202. Happy Number](https://leetcode.com/problems/happy-number/description/)
# 思路
按照题目的意思进行循环判断每次循环结果是否为1若是则返回true否则用map记录结果然后修改n进行下一次循环。
# C++
``` C++
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;
}
};
```