在整数 C++ 中查找出现频率最低的数字

Look for least frequent digit in an integer C++

我必须首先说明我的问题有一条规则 - 不能使用函数、循环、数组以外的任何东西。

这是我目前拥有的:

#include <iostream>
using namespace std;
int getLeastOccurredDigit(int);

int main()
{
    int uIn;
    cout << "Enter an Integer: ";
    cin >> uIn;
    cout << "\nThe least occurred digit in " << uIn << " is " << getLeastOccurredDigit(uIn) << endl;
    return 0;
}

int getLeastOccurredDigit(int number)
{
    int freqList[10] = { 0 };
    int pNum = (number < 0) ? -number : number;
    while (pNum != 0)
    {
        freqList[(pNum % 10)]++;
        pNum /= 10;
    }
}

我基本上记录了数组中所有可能出现的数字 (0-9):

freqList[]

下一步当然是比较数组中的所有元素;忽略0,输出出现次数最少的数。

我不知道我该怎么做才能遍历数组,在忽略 0 的同时比较元素,并得出最小值。

        int getLeastOccurredDigit(int number)
        {
            int freqList[10] = { 0 };
            int pNum = (number < 0) ? -number : number;
            while (pNum != 0)
            {
                freqList[(pNum % 10)]++;
                pNum /= 10;
            }
        int MAX_FREQUENCY = (sizeof(int)*CHAR_BIT+2)/3;   
    /*(sizeof(int)*CHAR_BIT+2)/3 is an upper bound on the number of octal
      digits required for an int, and hence is an upper bound on the number 
   of decimal digits required for an int. by Martin Bonner [in comments]*/
            int small=MAX_FREQUENCY,index=0; 
            for(int i=1;i<10;i++)
            {
                if(small>freqList[i]&&freqList[i]!=0)
                {
                    index=i;
                    small=freqList[i];
                }
            }
            return index;
        }

既然你已经得到了回答,我会 post 替代版本,在那里你不仅受到数组的限制:

#include <iostream>
#include <string>
#include <map>

int LeastDigit(const int& num)
{
    std::string snum = std::to_string(num);
    std::map<char, size_t> occur;
    std::pair<char, size_t> result;

    for(auto& x : snum)
        occur[x]++;
    result = *occur.begin();

    for(auto& x : occur)
        if(x.second < result.second)
            result = x;

    return int(result.first-48);
}

int main()
{
    int num = 112233455, result;
    result = LeastDigit(num);
    std::cout << "Your digit: " << result << std::endl;
    return 0;
}

STL 让您的生活更轻松。