Happy Number

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 (1 sum of squares and 9)
82 + 22 = 68 (sum of squares of 8 and 2)
62 + 82 = 100 (sum of squares of 6 and 8) 12 + 02 + 02 = 1 (sum of
squares of 1 and 0 and 0)

Is to judge whether a positive integer is a Happy Number. Finds the sum of the squares of each bit of n, and returns true if it is 1. If it is not 1, then the other n = peace, and cycle in turn. If n is not Happy Number, it will keep looping, how to get out of this loop. You can put all the results in an array, and if the results of this time and the previous results are duplicates, return false to exit.

public static void main(String args[]){
		System.out.println(isHappy(7));
	}
	public static boolean isHappy(int n){
		ArrayList list=new ArrayList();
		if(n<=0)
			return false;
		if(n==1)
			return true;
		while(n!=1){
			int result=0;
			String s=String.valueOf(n);
			for(int i=0;i<s.length();i++){
				int t=Integer.parseInt(s.substring(i, i+1));
				result+=t*t;
			}
			n=result;
			list.add(n);
			/ / Determine whether the result of this time is the same as the previous result, if it is the same, return false to exit the infinite loop
			if(list.size()>=2){
				for(int i=0;i<list.size()-1;i++){
					if(list.get(i)==list.get(list.size()-1)){
						return false;
					}
				}
			}
		}
		return true;
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326357307&siteId=291194637