Sum of Digits in Base K


Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.

Example 1:
Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.

Example 2:
Input: n = 10, k = 10
Output: 1
Explanation: n is already in base 10. 1 + 0 = 1.

Constraints:
1 <= n <= 100
2 <= k <= 10

C++ Sum Digits of Base K

As we are converting from decimal to base K, we know exactly each digit and we can just sum them up along the process.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
    int sumBase(int n, int k) {
        int ans = 0;
        while (n > 0) {
            ans += n % k;
            n /= k;
        }
        return ans;
    }
};
class Solution {
public:
    int sumBase(int n, int k) {
        int ans = 0;
        while (n > 0) {
            ans += n % k;
            n /= k;
        }
        return ans;
    }
};

Python3 Sum Digits of Base K

Python code of iterating converting to Base K and suming the digits up. The Time complexity is tex_c79cab4088d28f00580d8a79b307e117 Sum of Digits in Base K algorithms c / c++ math python . The space complexity is O(1).

1
2
3
4
5
6
7
class Solution:
    def sumBase(self, n: int, k: int) -> int:
        ans = 0
        while n:
            ans += n % k
            n //= k
        return ans
class Solution:
    def sumBase(self, n: int, k: int) -> int:
        ans = 0
        while n:
            ans += n % k
            n //= k
        return ans

See also: Teaching Kids Programming – Binary Search Algorithm to Compute the Logarithm Base Two Function

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
334 words
Last Post: Teaching Kids Programming - Hour and Minute Angle on a Clock
Next Post: Teaching Kids Programming - Remove Vowels from a String

The Permanent URL is: Sum of Digits in Base K

Leave a Reply