【问题标题】:C++ Fast base convertions, digits countC++ 快速基础转换,数字计数
【发布时间】:2018-06-06 04:41:42
【问题描述】:

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

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,所以我可以轻松地将 return 传递给 countDigits 函数。而且我不知道如何计算输入数字。它应该尽可能高效。

【问题讨论】:

  • 也许你能解释更多?尤其是每个输出的计算方式。
  • 嗯,首先我计算数组的总和。总和计入主要。然后我使用函数转换,将总和转换为给定的基数。问题是我的函数 convert 是 void 类型,所以我不能将结果传递给函数 countDigits。因为如果可以的话,我将完成第一个输出:求和 -> 转换为基数 -> 计算数字。

标签: c++ count converter base


【解决方案1】:

我相信您需要一个功能: 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;
}

另外,还有一种方法是使用对数在固定时间内计算答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多