File tree Expand file tree Collapse file tree 2 files changed +120
-0
lines changed Expand file tree Collapse file tree 2 files changed +120
-0
lines changed Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text ;
5
+ using System . Threading . Tasks ;
6
+
7
+ namespace Leetcode_202_Happy_number
8
+ {
9
+ /// <summary>
10
+ /// Leetcode 202
11
+ /// Happy number
12
+ /// https://leetcode.com/problems/happy-number/description/
13
+ /// </summary>
14
+ class Program
15
+ {
16
+ static void Main ( string [ ] args )
17
+ {
18
+ var result = IsHappy ( 19 ) ;
19
+ }
20
+
21
+ public static bool IsHappy ( int n )
22
+ {
23
+ if ( n == 1 )
24
+ return true ;
25
+
26
+ var hashSet = new HashSet < int > ( ) ;
27
+
28
+ return isHappyHelper ( n , hashSet ) ;
29
+ }
30
+
31
+ private static bool isHappyHelper ( int n , HashSet < int > hashSet )
32
+ {
33
+ if ( n == 1 )
34
+ return true ;
35
+
36
+ if ( hashSet . Contains ( n ) )
37
+ return false ;
38
+
39
+ hashSet . Add ( n ) ;
40
+
41
+ return isHappyHelper ( getSumSquare ( n ) , hashSet ) ;
42
+ }
43
+
44
+ /// <summary>
45
+ /// 19
46
+ /// </summary>
47
+ /// <param name="n"></param>
48
+ /// <returns></returns>
49
+ private static int getSumSquare ( int n )
50
+ {
51
+ // base case
52
+ if ( n < 10 )
53
+ return n * n ;
54
+
55
+ var digit = n % 10 ; // 9
56
+
57
+ return getSumSquare ( n / 10 ) + digit * digit ;
58
+ }
59
+ }
60
+ }
Original file line number Diff line number Diff line change
1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text ;
5
+ using System . Threading . Tasks ;
6
+
7
+ namespace Leetcode_202_Happy_number
8
+ {
9
+ /// <summary>
10
+ /// Leetcode 202
11
+ /// Happy number
12
+ /// https://leetcode.com/problems/happy-number/description/
13
+ /// </summary>
14
+ class Program
15
+ {
16
+ static void Main ( string [ ] args )
17
+ {
18
+ var result = IsHappy ( 19 ) ;
19
+ }
20
+
21
+ public static bool IsHappy ( int n )
22
+ {
23
+ if ( n == 1 )
24
+ return true ;
25
+
26
+ var hashSet = new HashSet < int > ( ) ;
27
+
28
+ return isHappyHelper ( n , hashSet ) ;
29
+ }
30
+
31
+ private static bool isHappyHelper ( int n , HashSet < int > hashSet )
32
+ {
33
+ if ( n == 1 )
34
+ return true ;
35
+
36
+ if ( hashSet . Contains ( n ) )
37
+ return false ;
38
+
39
+ hashSet . Add ( n ) ;
40
+
41
+ return isHappyHelper ( getSumSquare ( n ) , hashSet ) ;
42
+ }
43
+
44
+ /// <summary>
45
+ /// 19
46
+ /// </summary>
47
+ /// <param name="n"></param>
48
+ /// <returns></returns>
49
+ private static int getSumSquare ( int n )
50
+ {
51
+ // base case
52
+ if ( n < 10 )
53
+ return n * n ;
54
+
55
+ var digit = n % 10 ; // 9
56
+
57
+ return getSumSquare ( n / 10 ) + digit * digit ;
58
+ }
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments