LEETCODE-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.

Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

还没有看到哈希表,在这里用了一个偷懒的方法——用i去记录相加的次数,如果次数太多则认定为false;
等看完哈希表再来完善

class Solution {
public:
    bool isHappy(int n) {
        int i = 0;
    while (1) {
        int sum = 0;
        while (n != 0) {
            int x = n % 10;
            sum = sum + x * x;
            n = n / 10;
        }
        n = sum;
        if (n == 1)
            return 1;
        else
            i++;
        if (i == 25)
            return 0;
    }
    }
};
这段代码是一个判断“快乐数”的算法实现。“快乐数”是指通过不断替换该数,将其每一位数字的平方和求出新的值,并最终能够收敛到1的正整数。 ### 具体解释: #### 函数功能分解: 1. `get_next(n)` - 这个内部函数用于计算给定数字`n`的所有位上数字的平方之和。例如,对于输入23,则会返回 \(2^2 + 3^2 = 4+9=13\)。 ```python def get_next(n): total_sum = 0 while n > 0: n, digit = divmod(n, 10) # 取得最后一位digit并将原数值去掉这一位 total_sum += digit ** 2 # 将当前取得的digit做平方并加总 return total_sum ``` 2. 主函数部分从初始数字开始进入循环,每次调用`get_next()`得到一个新的值。如果这个新值得到了已经见过的情况(即陷入了一个循环),那么就不是“快乐数”。若成功到达了1则认为是“快乐数”。 ```python seen = set() # 使用集合记录曾经出现过的中间结果避免无限循环 while n != 1 and n not in seen: seen.add(n) n = get_next(n) return n == 1 ``` 当且仅当循环结束时`n==1`, 判断其为"快乐数". #### 算法原理简述: - 每次迭代都将原始数据替换成它的各个位置上所有数码二次幂相加之后的所得的新数值. - 如果某一次的结果等于1, 那么按照定义这就是所谓的幸福(快活)号码; 否则假如发现有重复项出现在set容器内表明陷入了无尽轮回当中无法跳出此过程达到稳定状态. ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值