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
program main
implicit none
integer :: n, k, result
! Example 1
n = 34
k = 6
write (*, '(A, I0, A, I0, A, I0)') 'n = ', n, ', k = ', k, ', result = ', sum_digits(n, k)
! Example 2
n = 10
k = 10
write (*, '(A, I0, A, I0, A, I0)') 'n = ', n, ', k = ', k, ', result = ', sum_digits(n, k)
contains
function sum_digits(n, k) result(result)
implicit none
integer, value :: n, k
integer :: result
integer :: i, digit
result = 0
do i = 1, len(n)
digit = modulo(n / (k ** (i - 1)), k)
result = result + digit
end do
end function sum_digits
end program main
temp.f95:26:22: 26 | do i = 1, len(n) | 1 Error: βstringβ argument of βlenβ intrinsic at (1) must be CHARACTER
```
program sum_digits
implicit none
integer :: n, k, i, sum
character(len=10) :: num
read(*,*) n, k
! Convert n from base 10 to base k
num = ''
do while (n > 0)
num = char(ichar('0') + mod(n, k)) // num
n = n / k
end do
! Sum the digits of num in base 10
sum = 0
do i = 1, len_trim(num)
sum = sum + ichar(num(i:i)) - ichar('0')
end do
! Output the sum
write(*,*) sum
end program sum_digits
```
temp.f95:1:2: 1 | ``` | 1 Error: Invalid character in name at (1) temp.f95:26:2: 26 | ``` | 1 Error: Invalid character in name at (1)
def sum_base(n: int, k: int) -> int:
s = 0
while n:
s += n % k
n //= k
return s
The algorithm is straightforward for converting a number from base 10 to base k and summing its digits. We use a while loop to repeatedly divide the number n by k, until n becomes 0. In each iteration, we add the remainder (n % k) to the sum, and update n by dividing it by k and taking the floor of the result. In the end, we return the sum.
int sumBase(int n, int k) {
int sum = 0;
while (n > 0) {
sum += n % k;
n /= k;
}
return sum;
}
The algorithm is straightforward for converting a number from base 10 to base k and summing its digits. We use a while loop to repeatedly divide the number n by k, until n becomes 0. In each iteration, we add the remainder (n % k) to the sum, and update n by dividing it by k and taking the floor of the result. In the end, we return the sum.