Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

202. Happy Number #137

Open
Tcdian opened this issue Apr 30, 2020 · 1 comment
Open

202. Happy Number #137

Tcdian opened this issue Apr 30, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 30, 2020

202. Happy Number

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False

Example

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 30, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    const cache = new Set();

    while (n !== 1) {
        n = calcSquareOfDigitSum(n);
        if (cache.has(n)) {
            return false;
        }
        cache.add(n);
    }

    return true;
};

function calcSquareOfDigitSum(n) {
    let result = 0;
    while (n !== 0) {
        result += Math.pow((n % 10), 2);
        n = Math.floor(n / 10);
    }
    return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant