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 sum 24 public int getsum(int[] arr){ 25 int sum = 0; 26 for(int ii = 0;ii<arr.length;ii++){ 27 sum = sum + arr[ii]*arr[ii]; 28 } 29 return sum; 30 } 31 32 33 //get numbers 34 public int[] test(int n){ 35 String s = String.valueOf(n); 36 int count = s.length(); 37 int[] arr = new int [count]; 38 39 for(int i = 0;i<count;i++){ 40 String sc = s.substring(i, i+1); 41 int is = Integer.parseInt(sc); 42 arr[i] = is; 43 // System.out.println("arr:"+arr[i]); 44 } 45 // System.out.println("--------"); 46 47 return arr; 48 49 } 50 }
392 ms.