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
1.把数字各位放入数组,test(int n)方法.
2.计算各位之平方和,getsum(int[] arr)方法.
3.判断结束条件。
1 public class Solution { 2 public boolean isHappy(int n) { 3 4 int times=0; 5 int[] arr = test(n); 6 7 int sum = getsum(arr); 8 9 while(sum!=1){10 int[] ar = test(sum);11 sum = getsum(ar);12 times++;13 if(times>100){ //loop times,>100 loops endlessly in a cycle,it works.14 return false;15 }16 }17 System.out.println(sum);18 19 return true;20 }21 22 23 //get sum24 public int getsum(int[] arr){25 int sum = 0;26 for(int ii = 0;ii
392 ms.