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.
編寫一個算法來定義一個數字 n 是否是快樂數字。 - 從任何正整數開始,將數字特換成平方和。 - 重複這個過程直到數字等於 1(它將保持不變),或者它在不包括 1 的循環中無限循環。 - 這個過程以 1 結束的那些數字就是快樂數字。 如果 n 是一個快樂的數字,則回傳 true,否則回傳 false。 ex. 「快樂數」是指將一個正整數的每個位數的平方相加,然後再對這個新的數字進行相同的操作,重複這個過程,如果最終能夠得到數字1,則該數字是「快樂數」。如果這個過程陷入循環而不會得到1,則該數字不是「快樂數」。
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
Solution:
1. 因為最終會以個位數進行判斷,而 1-9 中只有 1, 7 是快樂數字,所以設定 while(n > 6){},小於 6 的數值直接判斷是否為 1。
2. 將 n 透過 toString() 轉乘字串,並使用 split(“”) 將字串拆分出來,透過 forEach 來把每個數值平方後相加。
3. 如果 n 是個位數,則由 0 開始加總。
4. 最終判斷 n 是否等於 1。
Code 1:
var isHappy = function(n) { while (n > 6) { n.toString().split("").forEach(function(element, index) { if(index === 0) n = 0 n += element * element }) } return n === 1 };
FlowChart:
Example 1
Input: n = 19 n = 1^2 + 9&2 = 1 + 81 = 82 n = 8^2 + 2&2 = 64 + 4 = 68 n = 6^2 + 8&2 = 36 +64 = 100 n = 1^2 + 0^2 + 0^2 = 1 return n === 1 //true
Example 2
Input: n = 2 return 2 === 1 //false
toString():
const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // expected output: "1,2,a,1a"
split(“”):
const str = 'The quick brown fox jumps over the lazy dog.'; const words = str.split(' '); console.log(words[3]); // expected output: "fox"
// Code 2: bigO(n)
var isHappy = function (n) {
const set = new Set().add(1);
while (!set.has(n)) {
set.add(n);
let sum = 0;
for (let c of String(n)) {
sum += Number(c) * Number(c);
}
n = sum;
}
return n === 1;
};