LeetCode刷題EASY篇Happy Number
阿新 • • 發佈:2018-12-13
題目
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: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
十分鐘嘗試
我的嘗試思路,以前處理過int型別資料如何求出每一位,對,就是求mod運算,然後平方相加就可以。程式碼如下:
class Solution { public boolean isHappy(int n) { int res=0; while(true){ while(n>0){ int mod=n%10; res+=Math.pow(mod,2); n=n/10; } if(res==1){ return true; } n=res; } return false; } }
問題是無限迴圈,leetcode測試不通過。題目也說的是loop endlessly。不知道這個地方如何處理。看了他人對答案,用set.儲存當前的和,如果能add,繼續。另外,上面的程式碼有個問題,res應該在第一個while迴圈裡面,修改如下,完美通過;
class Solution { public boolean isHappy(int n) { Set<Integer> set=new HashSet(); while(set.add(n)){ int res=0; while(n>0){ int mod=n%10; res+=Math.pow(mod,2); n=n/10; } if(res==1){ return true; } n=res; } return false; } }