Create 202. Happy Number.md

This commit is contained in:
唐树森 2018-09-13 12:37:33 +08:00 committed by GitHub
parent cb30e5543e
commit 0ab039ab95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

28
202. Happy Number.md Normal file
View File

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