Created
December 31, 2017 11:43
-
-
Save tamlt2704/0593461715b5de5881bc5a2d91e728a0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 the result has only one digit. | |
| #For example: | |
| #Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. | |
| #Follow up: | |
| #Could you do it without any loop/recursion in O(1) runtime? | |
| class Solution(object): | |
| def addDigits(self, num): | |
| """ | |
| :type num: int | |
| :rtype: int | |
| """ | |
| def imod(x, y): | |
| s = 1 | |
| if x < 0: | |
| s = -1 | |
| return s * ((x*s) % y) | |
| return 1 + imod(num-1, 9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment