leercode202. 快乐数

xiaoxiao2025-04-13  13

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

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

示例: 

输入: 19 输出: true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1

 

#include<iostream> #include<unordered_set> using namespace std; class Solution{ public: bool isHappy(int n) { if (n<=0){ return false; } while (!mul.count(n)){ mul.insert(n); int sum = 0; while (n){ sum += (n % 10)*(n % 10); n /= 10; } if (sum == 1){ return true; } n = sum; } return false; } private: unordered_set<int> mul; }; int main() { bool reslut=Solution().isHappy(19); if (reslut){ cout << "Ture" << endl; } else { cout << "False" << endl; } return 0; }

 

转载请注明原文地址: https://www.6miu.com/read-5028194.html

最新回复(0)