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 and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.
Example:19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
This problem at first did not understand test instructions ... If it's not 1, it's not happy number. But it has to be added until the cycle is over ... So test instructions can't take it for granted. After understanding, it's good to do it.
Public classSolution { Public BooleanIshappy (intN) {intsum = 0; Set<Integer> s =NewHashset<>(); while(true) { intTMP = n 10; N= N/10; Sum= SUM + tmp *tmp; if(n = = 0) { if(Sum! = 1 &&s.contains (sum)) { Break; } Else if(Sum = = 1) { return true; } Else{s.add (sum); N=sum; Sum= 0; } } } return false; }}
Top solution and my solution are similar, but I feel my own readability better? Is that my illusion?
Top Solution:
Public BooleanIshappy (intN) {Set<Integer> Inloop =NewHashset<integer>(); intSquaresum,remain; while(Inloop.add (n)) {Squaresum= 0; while(N > 0) {remain= n%10; Squaresum+ = remain*remain; N/= 10; } if(Squaresum = = 1) return true; ElseN=squaresum; } return false;}
It has a better point is the hashset inside if there is already a number, the Add method will return false, this is not known, learned.
Happy number Leetcode