Skip to content

Commit 7230456

Browse files
committed
Add Happy Number solution
1 parent 8e052dc commit 7230456

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

0 commit comments

Comments
 (0)