题目描述
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.
题目大意:写一个算法判断一个数字是否是“happy”,happy number的定义如样例所示,最后的结果为1即为“happy”
样例
Example:
Input: 19
Output: true
Explanation:
1 2 + 9 2 1^2 + 9^2 12+92 = 82
8 2 + 2 2 8^2 + 2^2 82+22 = 68
6 2 + 8 2 6^2 + 8^2 62+82 = 100
1 2 + 0 2 + 0 2 1^2 + 0^2 + 0^2 12+02+02 = 1
python解法
class Solution:
def isHappy(self, n: int) -> bool:
dic = {n:0}
while True:
n = self.calc(n)
if n == 1:
return True
elif n in dic:
return False
else:
dic[n] = 0
def calc(self, n):
sum = 0
while n:
x = n % 10
sum += x ** 2
n = n // 10
return sum
Runtime: 36 ms, faster than 91.97% of Python3 online submissions for Happy Number.
Memory Usage: 13.8 MB, less than 5.26% of Python3 online submissions for Happy Number.
题后反思:
- 算法判断终止的条件就是计算过程中的结果出现了重复
C语言解法
struct List {
int val;
struct List *next;
};
void insert(struct List *d, int x)
{
struct List *p = (struct List*)malloc(sizeof(struct List));
p -> next = d -> next;
p -> val = x;
d -> next = p;
}
bool find(struct List *d, int x)
{
while(d -> next)
{
if (d -> next -> val == x)
return true;
d = d -> next;
}
return false;
}
int calc(int n)
{
int sum = 0;
int x = 0;
while (n)
{
x = n % 10;
sum += x * x;
n /= 10;
}
return sum;
}
bool isHappy(int n){
if (n == 1)
return true;
struct List *data[10] = {NULL};
for (int i=0;i<10;i++)
{
data[i] = (struct List*)malloc(sizeof(struct List));
data[i] -> next = NULL;
}
insert(data[n%10], n);
bool flag = false;
while (true)
{
n = calc(n);
if (n == 1)
{
flag = true;
break;
}
if (find(data[n%10], n))
break;
insert(data[n%10], n);
}
return flag;
}
Runtime: 0 ms, faster than 100.00% of C online submissions for Happy Number.
Memory Usage: 7.1 MB, less than 8.33% of C online submissions for Happy Number.
题后反思:无
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步