[英]How to return the integer with the lowest value that occurs the most frequently in an array?
我設法編寫了代碼來返回出現最多的數字,但是當多個數字出現的次數相同時,我需要返回具有最低值的那個。
int getFreq(int arg) {
int tmp;
int storage[10] = { 0 };
int maxDigit = -1;
int maxfreq = -1;
tmp = (arg < 0) ? -arg : arg;
do {
storage[tmp % 10]++;
if (storage[tmp % 10] > maxDigit) {
maxDigit = storage[tmp % 10];
maxFreq = tmp % 10;
}
tmp /= 10;
} while (tmp != 0);
return maxFreq;
}
我修改了您的函數,並將統計信息收集與其分析分開,以便輕松找到最頻繁但最低的數字。 6 和 7 都出現了兩次。 7 的括號括住所顯示數字中的 6,但該函數返回 6。
#include <stdio.h>
int getFreq(int arg) {
int tmp;
int storage[10] = { 0 };
int maxFreq = -1;
int digit = 0;
tmp = (arg < 0) ? -arg : arg;
do {
storage[tmp % 10]++;
tmp /= 10;
} while (tmp);
for (tmp=9; tmp>=0; tmp--) {
if (storage[tmp] >= maxFreq) {
digit = tmp;
maxFreq = storage[tmp];
}
}
return digit;
}
int main(void)
{
int val = 17266375;
printf("Most frequent (lowest) from %d = %d\n", val, getFreq(val));
return 0;
}
程序輸出:
Most frequent (lowest) from 17266375 = 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.