LeetCode 202 Happy Number
题目:
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:
解法:
1. 利用set保存每次计算的结果,若出现1,则返回true,若出现已有元素,而没有出现1则说明会陷入循环,返回false
class Solution { public boolean isHappy(int n) { Set<Integer> set = new HashSet<>(); int newn = 0; while(!set.contains(n)) { set.add(n); newn = 0; while(n>0) { newn += (n%10)*(n%10); n /= 10; } if(newn==1) return true; n = newn; } return false; } }
2. 参考了discussion的做法,经规律总结,当计算结果在10以内时,只有7和1才会是happy number
class Solution { public boolean isHappy(int n) { int newn = 0; while(n>9) { newn = 0; while(n>0) { newn += (n%10)*(n%10); n /= 10; } n = newn; } return n==7||n==1; } }