/*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, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: 19 is a happy number 12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1*/
import java.util.*; public class HappyNum { public static void main(String[] args) {
// TODO Auto-generated method stub System.out.println(isHappy(19)); } /**
* @param n
*/ public static int pingfanghe(int n) {
int sum = 0;
while (n != 0) {
sum += (n % 10) * (n % 10);
n = n / 10;
}
return sum;
} public static boolean isHappy(int n) {
/*
* int sum=0; char[] ch=String.valueOf(n).toCharArray(); for(int
* i=0;i<ch.length;i++) sum+=(ch[i])*ch[i]; //这样不行,返回的是asc码
* System.out.println(sum); if(n==1) return true; else return
* isHappy(n);
*/
/*
* if(n==1) return true; Set<Integer> al=new HashSet<Integer>(); int
* sum=0; while(n!=0) { al.add(n%10); n=n/10; } System.out.println(al);
* for(int i=0;i<al.size();i++) sum+=al.*al.get(i); n=sum;
* System.out.println(n);
*
*
*
* // return isHappy(n);
*
* return isHappy(n);
*/ Set<Integer> hs = new HashSet<Integer>();
while (true) {
if (hs.contains(n))
return false;
if (n == 1)
return true;
hs.add(n);
n = pingfanghe(n); } } }
注意:1.循环的判断
2.字符数组转化是不行的,输出的是asc码。
3.集合框架的使用