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
Test instructions: According to the above example, split the integer, get the sum of squares, if the final result is 1, stop, if the result is the number of previous existence (into an infinite loop), also stop;
Code
Package Leetcode;
Import java.util.*;
public class Happynumber {
Stop condition: Either sum=1, or the result contains sum;
Parse each number, use a mutable array to store the resulting results, and determine whether it is 1 or a loop?
the use of//while (true);
public static Boolean ishappy (int n) {
/*
* int res = 0; Map<integer, arraylist<integer>> map = new hashmap<> ();
*//Map.put (n, New arraylist<> ()); int sum = n; while (sum! = 1) {
* List arr = new ArrayList (); Map.put (Sum, New arraylist<integer> ());
* IF (Map.containskey (sum)) return false; if (n <= 9) {
* Map.get (SUM). Add (n); } else {while (n > 9) {res = n 10;
* Map.get (SUM). Add (res); n = N/10; }} Iterator ite = new Iterator ();
* for (int i = 0; i < map.get (sum). Size (); i++) {int tmp = (Integer)
* Map.get (SUM). get (i); sum + = tmp * TMP; }
*
*} return true;
*/
/* map<integer,arraylist<integer>> Map = new hashmap<> (); */
list<integer> arr = new arraylist<> ();
int sum = 0;
while (true) {
Sum + = (n%) * (n 10); Just to a number such analysis can!!
n = N/10;
if (n = = 0) {
if (Arr.contains (sum))
return false;
else if (sum = = 1)
return true;
Arr.add (sum);
n = sum;
sum = 0;
}
}
}
public static void Main (string[] args) {
TODO auto-generated Method Stub
System.out.println (Ishappy (7));
}
}
Leetcode-happy number