码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-09-13 22:22:42      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

 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      * 1
15      * 2-4-16-37-58-89-145-42-20-4
16      * 3-9-81-65-61
17      * 4
18      * 5-25-29-85-89
19      * 6-36-45-41-17-50
20      * 7-49-97-130-10
21      * 8-64-52-29
22      * 9-81-65
23      * 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 stub
41         System.out.println(isHappy(23456));
42     }
43 }

 

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

标签:

原文地址:http://www.cnblogs.com/luluqiao/p/5869849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!