[LeetCode]#1837. Sum of Digits in Base K

Environment: Python 3.8

Key technique: //, %

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.

Analysis:

  1. Calculate quotient and remainder between n and k.
  2. If update n > k, continue step1.
  3. If update n≤k, stop calculate.
  4. Summarize the current quotient and remainder.

Solution:

class Solution:
def sumBase(self, n: int, k: int) -> int:
ans=0
while (n>=k):
ans+=n%k
n//=k
return ans +n

Submissions:

Reference:

https://leetcode.com/problems/sum-of-digits-in-base-k/discuss/1345499/python-solution