Tuesday, August 8, 2017

258. Add Digits

https://leetcode.com/problems/add-digits/description/
Digital root : dr(n) = 1 + (n-1) % (b-1), where n is the base.
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);
    }

No comments:

Post a Comment