Created
April 23, 2022 18:36
-
-
Save Turskyi/69e144639859c8c2585110829d3f0a6c to your computer and use it in GitHub Desktop.
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given a non-negative integer, num, repeatedly add all its digits until it has a single digit remaining and return it. | |
Ex: | |
num = 123, return 6 (1 + 2 + 3 = 6) | |
Ex: | |
num = 8353, return 1 (8 + 3 + 5 + 3 = 19 = 1 + 9 = 10 = 1 + 0 = 1). | |
* */ | |
fun addDigits(num: Int): Int { // 23 | |
return (num - 1) % 9 + 1 // 23 - 1 = 22 // 22 % 9 = 4 // 4 + 1 = 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment