Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

K 进制表示下的各位数字总和 #247

Open
louzhedong opened this issue Apr 25, 2021 · 0 comments
Open

K 进制表示下的各位数字总和 #247

louzhedong opened this issue Apr 25, 2021 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

给你一个整数 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 <= 100
2 <= k <= 10

思路

进制问题,一般都采用递归

解答

/**
 * @param {number} n
 * @param {number} k
 * @return {number}
 */
var sumBase = function(n, k) {
    var stack = [];
    while(n >= k) {
        var b = n % k;
        stack.push(b);
        n = Math.floor(n / k);
    }
    stack.push(n);
    return stack.reduce(function(prev, next) {
        return prev + next;
    })
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant