LeetCode 题解工作台
K 进制表示下的各位数字总和
给你一个整数 n ( 10 进制)和一个基数 k ,请你将 n 从 10 进制表示转换为 k 进制表示,计算并返回转换后各位数字的 总和 。 转换后,各位数字应当视作是 10 进制数字,且它们的总和也应当按 10 进制表示返回。 示例 1: 输入: n = 34, k = 6 输出: 9 解释: 3…
1
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们将 除 取余,直至为 ,余数相加即可得到结果。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个整数 n(10 进制)和一个基数 k ,请你将 n 从 10 进制表示转换为 k 进制表示,计算并返回转换后各位数字的 总和 。
转换后,各位数字应当视作是 10 进制数字,且它们的总和也应当按 10 进制表示返回。
示例 1:
输入:n = 34, k = 6 输出:9 解释:34 (10 进制) 在 6 进制下表示为 54 。5 + 4 = 9 。
示例 2:
输入:n = 10, k = 10 输出:1 解释:n 本身就是 10 进制。 1 + 0 = 1 。
提示:
1 <= n <= 1002 <= k <= 10
解题思路
方法一:数学
我们将 除 取余,直至为 ,余数相加即可得到结果。
时间复杂度 ,空间复杂度 。
class Solution:
def sumBase(self, n: int, k: int) -> int:
ans = 0
while n:
ans += n % k
n //= k
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log_k(n)) because each division reduces n by a factor of k. Space complexity is O(1) if only using integer variables, or O(log_k(n)) if storing digits in an array for summation. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should immediately identify the need for base conversion.
- question_mark
Look for correct use of modulus and integer division for digit extraction.
- question_mark
Ensure the candidate handles edge cases where n < k or n is a multiple of k.
常见陷阱
外企场景- error
Attempting to convert n to a string in base k incorrectly, which can produce wrong sums.
- error
Forgetting to sum digits as base 10 numbers instead of characters or strings.
- error
Overcomplicating the solution by using arrays or recursion when a simple loop suffices.
进阶变体
外企场景- arrow_right_alt
Sum of digits in base k for very large n, requiring optimized iteration.
- arrow_right_alt
Compute the sum of squares of digits in base k instead of the sum.
- arrow_right_alt
Apply the same digit-sum logic for negative numbers using absolute values.