Write an algorithm to determine if a number is "happy".git
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.网络
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/happy-number
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。app
这道题的难点我以为就是,当各个数字的平方和sum不等于1时,不能直接退出。可是继续循环下去的时候又容易进入了一个死循环,所以,咱们能够设置一个set来存储出现过的平方和,当新算出来的平方和已经存在于此集合时,证实即将进入死循环,因此能够返回false,若是此平方和不曾出现过期,继续判断,同时把此数添加至set里面,而且把n更新为sum.less
代码以下:oop
class Solution { public boolean isHappy(int n) { Set<Integer> temp = new HashSet<>(); while(true) { int sum = 0; while(n != 0) { int m = n % 10; sum += m * m; n /= 10; } if(sum == 1) { return true; } else if(temp.contains(sum)) { return false; } else { temp.add(sum); n= sum; } } } }