[LeetCode]202. Happy Number ★

题目描述

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.
题后反思:

  1. 算法判断终止的条件就是计算过程中的结果出现了重复

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.
题后反思:无

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值