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
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
This topic is mainly to check whether an integer is happy number. One benefit is that the input must be a positive integer, regardless of the multiple input modes. Main ideas:
1. First of all, the number of input decomposition, split it into a, ten, hundred, thousands of separate, to facilitate the next step to calculate the sum of squares;
2. End Condition: If the value is happy number, then the termination condition is sum of 1 in a loop, if the value is not happy number, then the termination condition is a cycle, whether the sum obtained by this loop has been obtained in the previous loop, if it is obtained, then it must not be happy Number.
The code is as follows:
Public Staticarraylist<integer> L =NewArraylist<integer>(); Public Static voidPartintN) { if(n>=10) part (n/10); L.add (n%10); } Public Static BooleanIshappy (intN) {ArrayList<Integer> h =NewArraylist<integer>(); H.add (n); intsum = 0; intm =N; while(Sum!=1 &&!)h.contains (sum)) {h.add (sum); Sum= 0; L.clear (); Part (n); for(inti=0; I<l.size (); i++) {sum= sum + l.get (i) *L.get (i); } N=sum; } if(Sum = = 1) return true; Else return false; }
Leetcode--happy number