首页 > 代码库 > LeetCode----202. Happy Number(Java)

LeetCode----202. Happy Number(Java)

 1 package isHappy202; 2 /* 3  * Write an algorithm to determine if a number is "happy". 4 A happy number is a number defined by the following process:  5 Starting with any positive integer, replace the number by the sum of the squares of its digits,  6 and repeat the process until the number equals 1 (where it will stay),  7 or it loops endlessly in a cycle which does not include 1.  8 Those numbers for which this process ends in 1 are happy numbers. 9  */10 11 public class Solution {12     /*13      * solution:14      * 115      * 2-4-16-37-58-89-145-42-20-416      * 3-9-81-65-6117      * 418      * 5-25-29-85-8919      * 6-36-45-41-17-5020      * 7-49-97-130-1021      * 8-64-52-2922      * 9-81-6523      * so only 1 and 7 is "happy"24      */25     public static boolean isHappy(int n) {26         while(n/10>0){27             int sum=0;28             while(n/10>0){29                 sum+=Math.pow((n%10),2);30                 n=n/10;31             }32             sum+=Math.pow(n,2);33             n=sum;    34         }35         if (n==1||n==7)36             return true;37         return false;38     }39     public static void main(String[] args) {40         // TODO Auto-generated method stub41         System.out.println(isHappy(23456));42     }43 }

 

LeetCode----202. Happy Number(Java)