如何找到一个整数的最大频率

How do I find the max frequency of a number of an integer?

本文关键字:整数 频率 一个 何找      更新时间:2023-10-16

这是我到目前为止的代码:

 #include <iostream>
    #define MAX(X,Y) ((X) > (Y) ? (X):(Y))
    int frequency(int n);
    int main()
    {
        int x;
        std::cout << "Please enter a sequence of numbers."
            << std::endl;
                std::cin >> x;
        std::cout << "The max frequency of " << x << " is "
              << frequency(x)
                << std::endl;
        return 0;
    }
    int frequency(int n)
    {
        int A[10] = {0}, rem;
        while (n != 0)
        {
            int rem = (n % 10);
            A[rem] += 1;
            n = (n / 10);
            std::cout << rem <<  't' << n
                << std::endl;
        }
        //MAX(A[rem], n);
    }

我如何修改它,使它打印出在用户指定的整数中出现次数最多的数字?

只需跟踪循环中的最大值:

    int A[10] = {};
    int max = 0;
    while (n != 0)
    {
        int rem = n % 10;
        ++A[rem];
        n /= 10;
        if( max == rem or A[max] > A[rem] )
            continue;
        if( A[rem] > A[max] or rem > max )
            max = rem;  
    }
    return max;

请注意,您创建了另一个rem和数组,您最好删除它,因为您不使用它。

注释2:

没有问题
 A[rem] += 1;
 n = ( n / 10 );

可以在c++中简单地表示,如我的代码所示。