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
K 进制表示下的各位数字总和。
给你一个整数 n(10 进制)和一个基数 k ,请你将 n 从 10 进制表示转换为 k 进制表示,计算并返回转换后各位数字的 总和 。
转换后,各位数字应当视作是 10 进制数字,且它们的总和也应当按 10 进制表示返回。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-digits-in-base-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
又来做周赛了,这是第一题。直接给代码。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int sumBase(int n, int k) { 3 int res = 0; 4 while (n != 0) { 5 res += n % k; 6 n /= k; 7 } 8 return res; 9 } 10 }