快乐数
题目
编写算法来判断数 n n n是不是快乐数
思路
- g e t N u m getNum getNum函数,进行得到下一次计算结果;
- 当计算结果不是在之前的循环中的数时,继续进行计算;否则,返回 f a l s e false false;
- 因为不要求有序,数字可能很大,且只用存储一个值,因此使用 unordered_set
具体代码
CPP
class Solution {
public:
bool isHappy(int n) {
int sum = 0;
sum = getNum(n);
set<int> res;
while (sum != 1) {
// 如果循环,那么不是快乐数
if (res.find(sum) != res.end())
return false;
else {
res.insert(sum);
sum = getNum(sum);
}
}
return true;
}
//如何实现sum函数
int getNum(int n) {
int sum = 0;
while (n) {
// 取个位上的平方
sum += (n % 10) * (n % 10);
// 右移一位
n /= 10;
}
return sum;
}
};
#include <iostream>
#include <unordered_set>
#include <cmath>
using namespace std;
class Solution
{
public:
bool isHappy(int n)
{
unordered_set<int> hash;
while (n != 1)
{
hash.insert(n);
n = getNum(n);
if (hash.find(n) != hash.end())
return false;
}
return true;
}
int getNum(int n)
{
int res = 0;
string s = to_string(n);
for (int i = 0; i < s.size(); i++)
{
res += pow(s[i] - '0', 2);
}
return res;
}
};
int main()
{
Solution s;
cout << s.isHappy(19) << endl;
Solution s2;
cout << s2.isHappy(2) << endl;
Solution s3;
cout << s3.isHappy(7) << endl;
Solution s4;
cout << s4.isHappy(1111111) << endl;
system("pause");
return 0;
}
Java
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] res) {
Solution n = new Solution();
n.isHappy(19);
}
}
class Solution {
public boolean isHappy(int n) {
if (n == 1) {
return true;
}
Set<Integer> hash = new HashSet<>();
hash.add(n);
while (n != 1) {
int next = getTransform(n);
if (hash.contains(next)) {
return false;
} else {
hash.add(next);
}
n = next;
}
return true;
}
public int getTransform(int n) {
int res = 0;
while (n != 0) {
int cur = n % 10;
res += cur * cur;
n /= 10;
}
return res;
}
}