
這題需要把數字每個位數拆出來做平方相加,如果得出結果是1,就是快樂數字。
LeetCode 題目連結
https://leetcode.com/problems/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, 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.
Return True if
n is a happy number, and False if not.
Example:
Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
Accept 作法
Runtime: 2 ms
Memory: 37.2 MB
Java 程式碼
class Solution {
public boolean isHappy(int n) {
int lastNum = n;
HashSet<Integer> set = new HashSet<Integer>();
while(lastNum != 1){
String numStr = String.valueOf(lastNum);
int sum = 0;
for(int i = 0; i< numStr.length();i++){
char ch = numStr.charAt(i);
int singleNum = Integer.parseInt(String.valueOf(ch));
sum = sum + singleNum*singleNum;
}
lastNum = sum;
if(set.contains(lastNum)){
return false;
}
set.add(lastNum);
}
return true;
}
}
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言