Test instructions
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: is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
This is a new problem, my idea is direct simulation, to 1 return, if entered a cycle, it will never reach 1. How to detect this loop is a problem, point open tags, which is written in the classification is Hashtable, suddenly feel as long as the recording process has occurred in every square and can be. This square sum of the range can be estimated, int number range 32-bit under the upper limit is 4294967296, that is, 10 bits, 9*9*10 words also only 810, I open a 1000 array can do this work.
The whole simulation process is that
1. For each of the current number of loops to ask you square sum
2. If the sum of squares equals 1, then return True
3. If the sum of squares is not 1, go to the tag array to look for, if present, indicate that a loop has occurred, return false
4. Mark the array element of the subscript to indicate that it has occurred.
The following code:
public static Boolean ishappy (int n) { int[] hash = new int[1000]; for (int i=0;i<1000;i++) { hash[i] = 0; } int m = n; Boolean flag = false; while (true) { m=getsum (m); if (m==1) { flag = true; break; } else if (hash[m]==1| | M==n) {break ; } HASH[M] = 1; } return flag; } public static int getsum (int n) { int sum = 0; while (n>0) { int t = n%10; sum + = t*t; n/=; } return sum; }
Leetcode:happy number