Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 202. 快乐数 #66

Open
Animenzzzz opened this issue Sep 4, 2019 · 0 comments
Open

[LeetCode] 202. 快乐数 #66

Animenzzzz opened this issue Sep 4, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

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

示例: 

输入: 19
输出: true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

解题思路:循环拆解整数进行相加。需要注意,使用map存出现了个位的情况,如果下次再出现,说明要死循环了,直接return false。

C++解题:

class Solution {
public:
    bool isHappy(int n) {
        int orign = n,sum = 0;
        unordered_map<int,int> map;
        while(1){
            sum = 0;
            while(n){
                sum = (n%10)*(n%10)+sum;
                n = n/10;
            }
            if(sum == 1)return true;
            if(sum < 10){
                if(map[sum]) return false;
                else map[sum]++;
            }
            n = sum;
        }
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant