Skip to content

Commit 9594450

Browse files
committed
happy number
1 parent 8777f20 commit 9594450

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Math/Math.Lib/HappyNumber.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* ==============================================================================
2+
* 功能描述:PowerOfTwo
3+
* 创 建 者:gz
4+
* 创建日期:2017/5/8 18:58:49
5+
* ==============================================================================*/
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Text;
10+
11+
namespace Math.Lib
12+
{
13+
Write an algorithm to determine if a number is "happy".
14+
15+
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.
16+
17+
Example: 19 is a happy number
18+
19+
1^2 + 9^2 = 82
20+
8^2 + 2^2 = 68
21+
6^2 + 8^2 = 100
22+
1^2 + 0^2 + 0^2 = 1
23+
public class HappyNumberSln {
24+
public bool IsHappy(int n) {
25+
int slow =n, fast = n;
26+
do{
27+
slow = getSum(slow);
28+
fast = getSum(fast);
29+
fast = getSum(fast);
30+
}while(slow!=fast);
31+
return slow==1;
32+
}
33+
34+
public int getSum(int n){
35+
int sum=0;
36+
int tmp = n;
37+
while(tmp>0){
38+
int i = tmp%10;
39+
sum+=i*i;
40+
tmp = tmp/10;
41+
}
42+
return sum;
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)