December 14, 2023

Viiisit [LeetCode] - 202. Happy Number

#php#javascript#ruby

keep learning, keep coding!

Problem - Happy Number

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 則重複每位數開平方相加的動作,如果最後得到 1 的話,就是happy number,如果進入無限迴圈,這個數就不是 happy number。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
let seen = {};

// 檢查當前數字是否等於 1 或者是否已經在 seen 中
while (n !== 1 && !seen[n]) {
// 將當前數字加入 seen 中
seen[n] = true;
// 將數字轉為字串,再將字串轉為陣列,最後將陣列中的每個數字平方後相加
n = n.toString().split('').reduce((acc, cur) => acc + cur * cur, 0);
}

return n === 1;
};

Solution - Ruby

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
def is_happy(n)
seen = {}

while n != 1
return false if seen[n]
seen[n] = true

n = n.to_s.chars.map(&:to_i).map { |x| x**2 }.sum
end

n == 1
end

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
def is_happy(n)
return false if n <= 0
return true if n == 1
return false if n == 4
sum = 0
while n > 0
sum += (n % 10) ** 2
n /= 10
end
is_happy(sum)
end

為了避免無限循環,函數提前處理了一些特殊情況:如果 n 小於等於 0,返回 false;如果 n 等於 1,返回 true;如果 n 等於 4,返回 false。
使用 (n % 10) 獲取最後一位數字,計算其平方加到 sum 中,然後將 n 除以 10 去掉最後一位。這樣迭代直到 n 變成 0,然後遞迴調用 is_happy 函數檢查新的數字。

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function isHappy($n) {
$seen = [];

while ($n != 1) {
$sum = 0;

// 將數字的每一位數字的平方加到 $sum 中
while ($n > 0) {
$digit = $n % 10;
$sum += $digit * $digit;
$n = intval($n / 10);
}

// 如果在計算過程中發現已經存在,返回 false
if (isset($seen[$sum])) {
return false;
}

$seen[$sum] = true;
$n = $sum;
}

return true;
}

PHP 方法筆記

LeetCode 傳送門 - Happy Number