问题:
写一个算法来判断一个数是不是"快乐数"。
一个数是不是快乐是这么定义的:对于一个正整数,每一次将该数替换为他每个位置上的数字的平方和,然后重复这个过程直到这个数变为1,或是无限循环但始终变不到1。如果可以变为1,那么这个数就是快乐数。
样例:
例1:
输入:19 输出:true 说明: 19是一个快乐的数字 1 ^ 2 + 9 ^ 2 = 82 8 ^ 2 + 2 ^ 2 = 68 6 ^ 2 + 8 ^ 2 = 100 1 ^ 2 + 0 ^ 2 + 0 ^ 2 = 1
例2:
输入:5 输出:false 说明: 5不是一个快乐的数字 25->29->85->89->145->42->20->4->16->37->58->89 再次出现89。
python:
class Solution:
"""
@param n: An integer
@return: true if this is a happy number or false
"""
def changeResult(self, res):
resStr = str(res)
temp = []
for i in range(len(resStr)):
if resStr[i] != "0":
temp.append(resStr[i])
temp.sort()
return temp
def isHappy(self, n):
# write your code here
if n == 1:
return True
nStr = self.changeResult(n)
strList = []
while True:
for i in range(len(strList)):
if strList[i] == nStr:
return False
SUM = 0
for j in range(len(nStr)):
num = int(nStr[j])
SUM += pow(num, 2)
if SUM == 1:
return True
else:
strList.append(nStr)
nStr = self.changeResult(SUM)
C++:
class Solution {
public:
/**
* @param n: An integer
* @return: true if this is a happy number or false
*/
string changeResult(int res)
{
string resStr = to_string(res);
string temp = "";
for(int i = 0; i < resStr.size(); i++)
{
if(resStr[i] != '0')
{
temp = temp + resStr[i];
}
}
sort(temp.begin(), temp.end());
return temp;
}
bool isHappy(int n) {
// write your code here
if(n == 1)
{
return true;
}
string nStr = changeResult(n);
vector<string> strVec;
while(true)
{
for(int i=0; i< strVec.size(); i++)
{
if(strVec[i] == nStr)
{
return false;
}
}
int sum = 0;
for(int j=0; j< nStr.size(); j++)
{
int num = nStr[j] - '0';
sum += pow(num, 2);
}
if(sum == 1)
{
return true;
}else{
strVec.push_back(nStr);
nStr = changeResult(sum);
}
}
}
};