leetcode Happy Number
阿新 • • 發佈:2018-12-07
Happy Number 題目: https://leetcode.com/problems/happy-number/
解題思路:
1.新建一個set,儲存計算過程中獲得值
如果元素!=1 && 不再set中 加入set集合,計算累加和獲得新的值, 最終如果是快樂數最終結果為1,如果不是快樂數,最終結果不為1.
public static void main(String[] args) { int n=19; boolean happy = isHappy(n); System.out.println(happy); } public static boolean isHappy(int n) { Set<Integer> set=new HashSet<>(); while(n!=1 && !set.contains(n)){ set.add(n); n=getSum(n); System.out.println(n); } return n==1; } /** * 獲取各個元素的累加和 * @param n * @return */ public static int getSum(int n){ int result=0; while(n!=0){ int ge=n%10; result+=Math.pow(ge,2); n/=10; } return result; }