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
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
题意:[百度百科] 快乐数(happy number)有以下的特性:在给定的进位制下,该数字所有数位(digits)的平方和,得到的新数再次求所有数位的平方和,如此重复进行,最终结果必为1。
非快乐数的特点: 不是快乐数的数称为不快乐数(unhappy number),所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。
思路: 这里采用两种解法,
①: 第一种用C语言,利用了非快乐数最后都会进入上述循环的特点;
②: 第二种采用C++,老老实实按照原有思路,利用关联容器set帮助解答.
第一种C语言解法:
bool isHappy(int n) {
int sqrtDigit = 0;
int number = n;
int mod;
while(1)
{
sqrtDigit = 0;
while(0 != number)
{ //!< 平方和
mod = number%10;
number /= 10;
sqrtDigit += mod * mod;
}
if( 1 == sqrtDigit)
return 1;
else if ( 4 == sqrtDigit) //!<非快乐数最终都会进入包含4的数字循环
return 0;
number = sqrtDigit;
}
return 0;
}
第二种C++解法:
class Solution {
public:
bool isHappy(int n) {
int sqrtDigit = 0;
int number = n;
int mod;
set<int> sqrtOutcome;
sqrtOutcome.insert(n);
while(1)
{
sqrtDigit = 0;
while(0 != number)
{ //!< 计算平方和
mod = number%10;
number /= 10;
sqrtDigit += mod * mod;
}
if( 1 == sqrtDigit)
return 1;
else if(sqrtOutcome.count(sqrtDigit))
{ //!< 查看当前结果是否已经在set容器中
return 0;
}
sqrtOutcome.insert(sqrtDigit);
number = sqrtDigit;
}
return 0;
}
};