# 202 Happy Number

15 算出 1² + 5² 可以先拆解成 15%10 + Math.floor(15/10)

LeetCode

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: 
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 02 = 1

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

Edge Case

  • 可能會有一樣的值 [1, 2, 1]

  • 如果只有一個值 [1]

  • 值不是數字 ( 但題目已經說一定是數字所以這種狀況就不用再判斷了 )

怎麼解

  • 使用一個 set 儲存計算過的數字,如果目前的數字已經計算過,表示無窮迴圈出現,return false。

  • 怎麼把 21 拆成 2, 1 然後個別做運算呢? 直覺會想 .toString().split('').forEach 先轉成字串再轉陣列再用陣列方法解

改善

先轉成字串再轉陣列再用陣列方法解",轉來轉去之中也影響了效能。其實可以這樣做,先從個位數算再算十位數,效能也隨之增加

學到什麼?

input 若是一個數字,而要針對個別數字做運算,就可以考慮以上方法

Last updated

Was this helpful?