[Algorithm] 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.

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100

 

Handle the number directly, common way is thougth % or / operator

复制代码
/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    let memo = {};
    
    while(n !== 1 && !memo[n]) {
        memo[n] = true;
        let sum = 0;
        while(n > 0) {
            sum += (n % 10) *(n % 10);
            n = Math.floor(n / 10);
        }
        n = sum;
    }
    
    return n == 1;
};
复制代码

 

Second way:

复制代码
/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    return helper(n, {});
};

function helper(n, memo) {
    const ary = `${n}`.split('');
    let sum = 0;
    for (let n of ary) {
        sum += Math.pow(parseInt(n, 10), 2);
    }
    
    if (sum === 1) {
        return true;
    }
    
    if (sum in memo) {
        return false;
    }
    memo[sum] = true;
    return helper(sum, memo);
}
复制代码

 

posted @   Zhentiw  阅读(126)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-12-17 [Algorithm] Write a Depth First Search Algorithm for Graphs in JavaScript
2018-12-17 [Algorithms] Refactor a Loop in JavaScript to Use Recursion
2018-12-17 [Bash] Understand and Use Functions in Bash
2018-12-17 [Javascript] Await a JavaScript Promise in an async Function with the await Operator
2017-12-17 [Python] Array Attributes of Numpy lib
2017-12-17 [Python] Generating random numbers using numpy lib
2017-12-17 [Python] Normalize the data with Pandas
点击右上角即可分享
微信分享提示