nice-people-frontend-community / nice-js-leetcode

好青年 | leetcode 今日事今日毕(✅ Solutions to LeetCode by JavaScript, 100% test coverage, runtime beats 100% / LeetCode 题解 / GitHub Actions集成LeetCode每日一题至issues)
https://nice-people-frontend-community.github.io/nice-js-leetcode/
17 stars 1 forks source link

leetcode 202.快乐数 #38

Open webVueBlog opened 2 years ago

webVueBlog commented 2 years ago

image 202. 快乐数

webVueBlog commented 2 years ago

202. 快乐数

/*
 * @lc app=leetcode.cn id=202 lang=javascript
 *
 * [202] 快乐数
 */

// @lc code=start
/**
 * @param {number} n
 * @return {boolean}

(68 ms)
 */
// var isHappy = function(n) {
//     var seen = {};
//     while (n !== 1 && !seen[n]) {
//         seen[n] = true;
//         n = sumOfSquares(n);
//     }
//     return n === 1 ? true : false;
// };

// function sumOfSquares(numString) {
//     return numString.toString().split('').reduce(function(sum, num) {
//         return sum + Math.pow(num, 2);
//     }, 0);
// }

var isHappy = function(n) {
    if (n === 1) return true
    let p = getNext(n)
    let q = getNext(getNext(n))
    while (p !== q && q !== 1) {
        p = getNext(p)
        q = getNext(getNext(q))
    }
    return q === 1
};

// 获取下一个节点
var getNext = function(n) {
    let sum = 0;
    while (n) {
        sum += (n % 10) ** 2
        n = Math.floor(n / 10)
    }
    return sum
}

// @lc code=end