Breon Thibodeaux - 3 months ago 30

C++ Question

This is the code as a whole. It takes an integer x and returns the most common digit within the integer x, also in the case of a tie it returns the greater value.

`#include <iostream>`

using namespace std;

int max_frequency(int x)

{

int a[] = {0,0,0,0,0,0,0,0,0,0};

int temp, max;

while(x > 0)

{

temp = x%10;

x=x/10;

a[temp]++;

}

max = 0;

for(int i = 1; i < 10; i++)

{

if(a[i] >= a[max])

{

max = i;

}

}

return max;

}

int main()

{

int x;

cout << "Enter the integer: "<< endl;

cin >> x;

cout << max_frequency(x) << endl;

return 0;

}

The part I am confused about:

`int max_frequency(int x)`

{

int a[] = {0,0,0,0,0,0,0,0,0,0};

int temp, max;

while(x > 0)

{

temp = x%10;

x=x/10;

a[temp]++;

}

max = 0;

I understand that the array of 0's serves as a counter, what i don't understand is what's being assigned to the variable temp, and why. I had some help writing this code but it wasn't clearly explained to me what was going on here. If someone wouldn't mind explaining this piece, i'd greatly appreciate it. Thank you.

Answer

The `%`

is the modulo operator, meaning `x%y`

equals to the remainder of the division of x by y. In that case, we can see that `x%10`

returns the right-most digit of x, right? Now we can count the digits of a number