Day 18 - LeetCode 202. Happy Number

LeetCode 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: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

翻譯

判斷一個數字是否為happy number。
happy number 定義如下:當一個數的每位數平方後相加,大於1則重複每位數開平方相加的動作,如果最後得到1的話,這個數就是happy number,如果進入無窮迴圈,這個數就不是happy number。

想法

用陣列把數字都存起來, 如果有重複就代表會進入無窮迴圈, 那就不是happy number.

詳細參閱

https://skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/202md.html
https://discuss.leetcode.com/topic/73828/java-code-beating-95


Code

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {

    let map = [];

    while ( n != 1 ) {
        map.push(n);

        n.toString().split('').forEach(function(value, key){
            if ( key == 0 ) {
                n = 0;
            }
            n += Math.pow(value, 2);
        });

        if ( map.indexOf(n) > -1 ) {
            return false;
        }
    }
    return true;
};

Run


@ 找工作看職缺看公司花了一堆時間
@ 眼壓又開始高了
@ 吃了抗過敏的藥又腦子昏昏
@ 進度進展速度又慢了

留言