File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
kotlin/Fast and Slow Pointers Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun happyNumber (n : Int ): Boolean {
2
+ var slow = n
3
+ var fast = n
4
+ while (true ) {
5
+ slow = getNextNum(slow)
6
+ fast = getNextNum(getNextNum(fast))
7
+ if (fast == 1 ) {
8
+ return true
9
+ // If the fast and slow pointers meet, a cycle is detected.
10
+ // Hence, 'n' is not a happy number.
11
+ } else if (fast == slow) {
12
+ return false
13
+ }
14
+ }
15
+ }
16
+
17
+ fun getNextNum (x : Int ): Int {
18
+ var nextNum = 0
19
+ var num = x
20
+ while (num > 0 ) {
21
+ // Extract the last digit of 'x'.
22
+ val digit = num % 10
23
+ // Truncate (remove) the last digit from 'x' using floor
24
+ // division.
25
+ num / = 10
26
+ // Add the square of the extracted digit to the sum.
27
+ nextNum + = digit * digit
28
+ }
29
+ return nextNum
30
+ }
You can’t perform that action at this time.
0 commit comments