Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 23, 2022 18:36
Show Gist options
  • Save Turskyi/69e144639859c8c2585110829d3f0a6c to your computer and use it in GitHub Desktop.
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.
/*
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