Digital root : dr(n) = 1 + (n-1) % (b-1), where n is the base.
Solution O(1):
int addDigits(int num) {
Solution O(1):
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
Solution using loop/recursion:
int addDigits(int num) {
if(num<10) return num;
int s=0;
while(num!=0){
s+=num%10;
num/=10;
}
return addDigits(s);
}
Solution using loop/recursion:
int addDigits(int num) {
if(num<10) return num;
int s=0;
while(num!=0){
s+=num%10;
num/=10;
}
return addDigits(s);
}
No comments:
Post a Comment