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/