1. First question
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.
2.happy number
(First of all, the characteristics of happy number, the problem is not used for the time being.) )
If a number is happpy, then all of the squared and composed sequences that are calculated during validation are happy number. For example, 19 is happy number, and (82,68,100) is also. If a number is not, the same ... Neither the square nor the sequence. And happy number each is re-assembled, the new numbers are happy. (e.g. 91). Insert 0 at any location in Happy number, and the new numbers are happy.
See Http://en.wikipedia.org/wiki/Happy_number for a detailed introduction to happy number
3. Analysis
3.1 End condition
If a number, the sum of the squares of each digit is equal to 1, the number is happy, and if there is no sum equal to 1 in the process of the calculation, and there is a loop, it is not happy.
3.2 The values in the squared and sequence,hashset<> that can be computed with HashSet records cannot be duplicated and have no order, and the capacity will grow automatically on demand.
4. Code
public boolean ishappy (int n) {
if (n<=0) return false;
Hashset<integer> showednum=new hashset<> ();
while (N<=integer.max_value) {
if (Showednum.contains (n)) return false;
else Showednum.add (n);
N=digitsquare (n);
if (n==1) {
SYSTEM.OUT.PRINTLN ("yes");
return true;
}
}
return false;
}
public int Digitsquare (int n) {
int s=0,temp;
while (n!=0) {
temp=n%10;
S+=temp*temp;
N=N/10;
}
return s;
}
[Leetcode] Happy number