C ++快速基本转换,数字计数

问题描述 投票:-2回答:1

我必须编写一个应用程序,其中用户给出数字数组的长度以及数组元素之和将被转换成的基数。然后用户给出一个数组。应用程序必须对给定元素求和,然后将总和转换为给定的基数并计算总和的数字。更重要的是,它还应该打印多少位数作为输入。所以例如一个

input is:
  3 10 // 3 - length, 10 - base
  1 2 3 // array
And the output:
1 // number of digits of the sum in base 10
6 // number of digits in input

另一个例子:

Input:
3 2
1 2 3
Output:
3 
5

我到目前为止所写的内容:

#include <iostream>

using namespace std;

void convert(int N, int b)
{
//int result = 0;
if (N == 0)
    return ;

int x = N % b;
N /= b;
if (x < 0)
    N += 1;
convert(N, b);

cout << (x < 0 ? x + (b * -1) : x);
return;

}

int countDigits(int number) {
    if (number < 10) {
        return 1;
}
int count = 0;
while (number > 0) {
    number /= 10;
    count++;
}
return count;

}

int main()
{
int n, d;
cin >> n >> d;

int a;
long long int sum = 0;

int count = 0;
while (count++ < n) {
    cin >> a;
    sum += a;
}

cout << "Sum: " << sum << endl << "Diff Base: ";

if (sum != 0)
{
    convert(sum, d);
    cout << endl;
}
else
    cout << "0" << endl;
return 0;

}

问题是我不知道如何将convert函数更改为int,因此我可以轻松地将返回值传递给countDigits函数。而且我也不知道如何计算输入数字。它应该尽可能高效。

c++ count converter base
1个回答
0
投票

我相信你需要一个功能:sum - >具有指定基数的数字。你将有更难的时间在一个未指定的基础上表示你的总和,然后计算它的数字。以下功能应涵盖广泛的基础。

int nr_digits_in_base(long long int N, int B)
{
    assert(B > 1);
    int nr_digits_to_represent_N_in_base_B = N < 0 ? 2 : 1;
    while (N /= B)
        nr_digits_to_represent_N_in_base_B++;
    return nr_digits_to_represent_N_in_base_B;
}

或者,有一种方法是使用对数来计算固定时间的答案。

© www.soinside.com 2019 - 2024. All rights reserved.