Created
November 17, 2017 23:49
-
-
Save shailrshah/56af9e3ba126c932ae55891876b12d6e to your computer and use it in GitHub Desktop.
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.
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
//Digit root Problem | |
//Congruence formula | |
public int addDigits(int n) { | |
int b = 10; | |
if(n == 0) return 0; | |
else if(n % (b - 1) == 0) return b-1; | |
else return n % (b - 1); | |
// or directly return 1 + (num - 1) % 9; | |
} | |
// Brute Force | |
public int addDigits2(int n) { | |
int ans = 0; | |
while(n > 9) { | |
int result = 0; | |
while(n > 0) { | |
result += n%10; | |
n/=10; | |
} | |
n = result; | |
} | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment