Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

202. Happy Number #53

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

把每次各个digit相加的和存放在hashset中,如果有重复,则证明出现了循环,返回false 。

public class Solution { public boolean isHappy(int n) { if(n <= 0) return false; HashSet set = new HashSet<>(); int res = n; while(res > 1) { if(set.contains(res)) { return false; } set.add(res); res = helper(res); } return true; } private int helper(int n) { int sum = 0; while(n > 0) { sum = sum + (int)Math.pow(n%10, 2); n = n/10; } return sum; } }

Shawngbk commented 7 years ago

airbnb twitter uber