任务是编写一个函数,该函数接受一个数字并找到该数字中重复次数最多的数字。它应该打印找到的数字及其重复的次数。
当两位数重复相同的次数时,我遇到了问题。
例如,对于给定的号码788995
,它应该返回8 -> 2 \\ 9 -> 2
我该如何打印?
这是功能:
void maxDigitInNumber (long long n)
{
if (n < MIN || n > MAX)
{
cout << -1;
return;
}
n = abs(n);
int numOfDigits = (int)log10(n)+1;
int digits[100];
int helper[100] = {0};
int counter = 0;
int maxSize = 0;
int number = 0;
for (int i = 0; i <= numOfDigits; i++)
{
digits[i] = n%10;
n /= 10;
}
for(int i = 0; i < numOfDigits; i++)
{
if(helper[i] == 0)
{
counter = 0;
for(int j = i; j < numOfDigits; j++)
{
if(digits[j] == digits[i])
{
counter++;
helper[j] = 1;
}
if(counter > maxSize)
{
maxSize = counter;
number = digits[i];
}
}
}
}
if (number == 0)
{
for (int i = 0; i < numOfDigits; i++)
{
cout << digits[i] << "->" << maxSize << endl;
}
}
else
{
cout << number << "->" << maxSize << endl;
}
}
答案 0 :(得分:3)
在选择最大值之前,您应该存储每个数字的计数。之后,您可以在所有计数中选择最大值,并打印与最大值匹配的所有条目:
int count[10] = {0};
do {
count[n%10]++;
n /= 10;
} while (n != 0);
int maxCount = 0;
for (int i = 0 ; i != 10 ; i++) {
maxCount = max(maxCount, count[i]);
}
bool first = true;
for (int i = 0 ; i != 10 ; i++) {
if (count[i] == maxCount) {
if (!first) {
cout << " \\\\ ";
} else {
first = false;
}
cout << i << "->" << maxCount;
}
}
答案 1 :(得分:2)
只有10位数字,因此数字中的数字直方图只占10个字。
// ....
int hist[10] = {}; // Full tally available for further analysis
int max_count = 0; // result.
int max_digit = -1;
for (int i = 0; i <= numOfDigits; i++)
{
int digit = n % 10;
if (++hist[digit] > max_count)
{
max_count = hist[digit]; // could also be ++max_count ;)
max_digit = digit;
}
n /= 10;
}
以下是您可以使用的一些算法:
// prints digits with a certain score:
void print_if_score_is(const int hist[10], int score)
{
for (int i = 0; i < 10; ++i)
if (hist[i] == score)
std::cout << " digit: " << i << ", score: " << score << "\n";
}
int get_next_best_score(const int hist[10], int score)
{
int new_max = -1;
for (int i = 0; i < 10; ++i)
if (hist[i] > new_max && hist[i] < score)
new_max = i;
return new_max;
}
用法:
// ....
std::cout << "Digit most frequently found: \n";
print_if_score_is(hist, max_count);
std:: cout << "next in list: \n";
int next_best = get_next_best_score(hist, max_count);
print_if_score_is(hist, next_best);
//...
答案 2 :(得分:1)
按照以下方式构建您的程序:
std::multiset
。 multiset
允许同一个键的多个条目。因此,对于数字788995,您最终会得到一个多重集{1:[5,7],2:[8,9]}