202. Happy Number - Easy
前往題目
想法
- 一直算新的數字,然後每次都存到
set
裡面 - 檢查是否有一樣的,有的話就代表進入
loop
了,因為數字一樣,算出來的結果就一樣
思路
- 循環直到當前數字為
1
- 每次循環都根據題目的公式算出新的值,然後檢查是否
hashset
裡面已經有了 - 有的話就代表無限迴圈
- 沒有的話就繼續
難得自己寫出來的題目:D
Code
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> computed = new HashSet<Integer>();
int current = n;
// 1 is true
while (current != 1) {
// Waiting to cut digits
int meat = current;
current = 0; // reset for new value
// Separate the digit and make the new value
while (meat > 0) {
// 平方加起來
current += Math.pow(meat % 10, 2);
// 更新肉
meat /= 10;
}
// 檢查是否已經有了
if (computed.contains(current)) return false;
// 加到set裡面
computed.add(current);
}
return true;
}
}
202. Happy Number - Easy
https://f88083.github.io/2024/03/13/202-Happy-Number-Easy/