[LeetCode] 1837. 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

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 }
复制代码

 

LeetCode 题目总结

posted @   CNoodle  阅读(158)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2020-04-25 [LeetCode] 369. Plus One Linked List
点击右上角即可分享
微信分享提示