Happy Number Problem description
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 = the
8 2 + 2 2 = the
6 2 + 8 2 = -
1 2 + 0 2 + 0 2 =1
Meaning: Determine whether the sum of squares and sums of all numbers for an integer is 1, and if not the sum of squares of all the numbers of sums is computed, either end up with 1 or infinite loops. If it's 1, it's happynum.
Algorithmic thinking
The Hashtable store is not a happynumber number in the calculation process, and the table is evaluated before each calculation to determine whether it is happynum. If it is not happynum, the loop is calculated and if it is stopped.
Algorithm implementation
Import java.util.Hashtable; Public class solution { Public BooleanIshappy (intN) {BooleanHappynum =false; Hashtable<integer, boolean> badnumdic =NewHashtable<integer, boolean> ();int sum=0; while(!happynum) {sum=0; while(N >0) {sum+ = (n%Ten) * (n%Ten); n = n/Ten; } System.out.println (sum);if(sum!=1) {if(Badnumdic.containskey (sum)) Break; Badnumdic.put (sum,false); }Else{Happynum =true; } n =sum; }returnHappynum; }}
Algorithm time
The surface looks like a two-layer cycle of time complexity, actually:
- The calculation of the outer loop is a finite constant
For example give a number 25, his calculation process is as follows:
1^2+9^2 = 29
2^2+9^2 = 85
8^2 + 5^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89 (and the third step is the same, so repeated, and in the program because we are stored in the Hashtable, so this ends)
- The inner loop is at most the number of digits of the maximum integer 2147483647 10, also constant
Run time is t (n) = O (1)
Demo results
publicstaticvoidmain(String[] args) { new Solution(); System.out.println(hn.isHappy(11111)); }
5
25
29
85
89
145
42
20
4
16
37
58
89
False
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode" Happy number