标签:
Write an algorithm to determine if a number is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
int型的数据有10位数字,最大的值即为,平方和为,所以个一个810大小的数组即可表示所以可能被计算出来的平方和。
给一个n值,先计算这个n的各位数的平方和,如果这个和以前出现过(m==n也算出现过),那么这个数就不是happy number。
原因:If a number is happy, then all members of its sequence are happy; if a number is unhappy, all members of the sequence are unhappy.
如果一个数是happy number,那么他的各位数字的顺序无论怎么颠倒,新的数仍然是happy number。同理,如果不是,无论怎么颠倒,也不是happy number。如果算出来的和以前算过,那么说明这一步是从那个和算过来的,现在从这个和再算的话,就又回去了,就是一个无限循环了。
bool isHappy(int n) {
bool hash[810] = {false};
int m = n;
while (1) {
int sum = 0;
while (m) {
sum += (m % 10) * (m % 10);
m /= 10;
}
if (sum == 1) return true;
else if (hash[sum] || m == n) return false;
hash[sum] = true;
m = sum;
}
return false;
}
标签:
原文地址:http://www.cnblogs.com/binarylu/p/4450225.html