开发者

What is the logic in this code?

I am having a hard time understanding the following code:

if ((number % 10)> max) //rem of 10
{
    max = (nu开发者_如何学Cmber % 10);
}
number /= 10;

Could you please help me with this?


I guess the code you posted is the body of a loop, like this:

int max = 0;
while (number != 0) {
    if (number % 10 > max) {
        max = number % 10;
    }
    number /= 10;
}

This loop finds the largest decimal digit of number. E.g. if number==152, you will get max==5 after the loop.


If the last digit of number is larger than max:

if ((number % 10)> max)

Then max equals the last digit

max = (number % 10);

Remove the last digit

number /= 10;

When you put this in a loop, it let's you find the largest digit in the number.


  • (number % 10), gives remainder of number on dividing by 10.
  • (number % 10) > max, means if the remainer is greater than max.

So if the remainder is greater than max, them make max the remainder as:

       max = (number % 10); 

And number/=10 is a shorthand of

 number = number/10; //same as number /= 10;

which divides number by 10, and saves the quotient in number.

There are other shorthands in C++ as well:

 a += x; // a = a + x;
 a -= x; // a = a - x;
 a *= x; // a = a * x;
 a %= x; // a = a % x; //if a and x are integral type, if they're built-in type.

If the type of a is class, then you can overload all these operators for your class.


The following code does the same job but in a more understandable way. It also runs faster as the number of divisions, which are computationally expensive, is minimized (each % in your code implicitly involves a division).

// given: a positive integer 'number'
// sought-for: the maximum decimal digit in 'number'
int maxReminder = 0;
while (number != 0) {
    // find the quotient of the division of 'number' by 10
    int divQuotient = number/10;
    // find the reminder of the division above
    int divReminder = number - divQuotient*10;
    if (divReminder > maxReminder) {
        // 'divReminder' is the new maximum reminder
        maxReminder = divReminder;
    }
    // prepare for the next iteration
    number = divQuotient;
}
// 'maxReminder' now holds the sought-for
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜