202.开心数(javascript)202.HappyNumber

原创
小哥 3年前 (2022-11-10) 阅读数 7 #大杂烩

leetcode: https://leetcode-cn.com/problems/happy-number/
写一个算法来确定一个数字。 n 这是一个快乐的数字吗。

“快乐数字” 定义为:

对于正整数,用每个位置的数字的平方和替换该数字。
然后重复此过程,直到数字变为 1,也可以是 无限循环 但它从未改变。 1。
如果此过程 结果为 1,那么这个数字就是幸福。
如果 n 是 快乐数 就返回 true ; 不,返回 false 。

Write an algorithm to determine if a number n 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.
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.
Return true if n is a happy number, and false if not.

示例 1:

输入:n = 19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

示例 2:

输入:n = 2
输出:false

Example 1:

Input: n = 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Example 2:

Input: n = 2
Output: false

根据主题,
第一种方法:将得到的数字除以十。-----余数的平方 加起来商代换得到的数。
最后一次返回是1^2 + 9^2 = 82
第二种方法:当出现重复值时,确定它不是一个快乐的数字;1何时,确定是快乐的数字。其他情况重复第二种,第一种方法

function getSum(i) {
    let sum = 0
    while (i > 0) {
        sum += Math.pow(i % 10, 2)
        i = Math.floor(i / 10)
    }
    return sum
}

function isHappy(n) {
    let newSet = new Set()
    while (1) {
        if (newSet.has(n)) {
            return false
        }
        if (n == 1) {
            return true
        }
        newSet.add(n)
        n = getSum(n)
    }
};

function getSum(i) {
    let sum = 0
    while (i > 0) {
        sum += Math.pow(i % 10, 2)
        i = Math.floor(i / 10)
    }
    return sum
}

function isHappy(n) {
    let newMap = new Map()
    while (1) {
        if (newMap.has(n)) {
            return false
        }
        if (n == 1) {
            return true
        }
        newMap.set(n,1)
        n = getSum(n)
    }
};
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除