c++ - 返回以点C++结尾的数字行中出现次数最多的数字

标签 c++

Return the element with most occurrence in a line of digits that ends with a dot (input by the user, such as: 124325329083437993247.). If more than one element satisfying the condition, return any of them. C++



我可以找到最多出现的次数,但无法返回元素本身。另外,我只是一行一行地输入元素,而不是一次输入...任何帮助,我们感激不尽。

顺便说一句,我是一个初学者,所以只想了解基础知识即可:)
char count_element(string s)
{
    int counter = 0;
    int arr[s.size()];
    for(int i = 0; i <s.size(); i++)
    {
        for(int j = i; j < s.size(); j++)
        {
            if(s[j] == s[i])
            {
                counter++;
            }
        }
        arr[i] = counter;
    }
    int M = arr[0];
    for(int i = 1; i < s.size(); i++)
    {
        if(M < arr[i])
            M  = arr[i];

    }
    return '0'; //max occurred element is to be returned```


最佳答案

试试这个:

char getMax(const char* line)
{

    int count[10] = {0};
    for (int i = 0; line[i] != '.'; i++)
    {
        int digit = line[i] - '0';
        count[digit]++;
    }

    int index = 0;
    for (int i = 1; i < 10; i++)
    {
        if (count[index] < count[i])
            index = i;
    }

    return '0' + index;
}

关于c++ - 返回以点C++结尾的数字行中出现次数最多的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437068/

相关文章:

c++ - 具有 3 个线程的 Acqrel 内存顺序

c++ - 如何在主窗口标签的对话框中显示QLineEdit的输入?

c++ - 在 Internet Explorer_Server (IWebBrowser2) 上拦截 WM_COMMAND(从加速器发送)

c++ - std::vectors 是线程安全的吗?

c++11数组传递给函数错误

C++ 11 委托(delegate)构造函数纯虚方法和函数调用——危险?

C++:如何做一个链表与结构作为参数传递?

c++ - 如何从基类指针调用派生类方法?

c++ - cpp 的 cout 中的 printf 格式等价物

c++ - 将结构上无序集中的选定字段存储到 vector