Let's keep it simple and consider multi-digit numbers only for the time being.
Let's say our number is 24589. We're going to get through this problem two digits at a time. We're going to have lastDigit and nextToLastDigit, which will represent the least- and next-to-least-significant digits, respectively. You remember how to get digits individually using modulo, right?
1 2 3 4 5 6 7 8 9
|
int theNum = 24589;
int lastDigit = theNum % 10; //this will be 9
theNum /= 10; //divide theNum by 10 and store the result in itself. theNum becomes 2458
int nextToLastDigit = theNum % 10; //this will be 8
theNum /= 10; //same story. theNum becomes 245.
//notice how we're using theNum to hold "the rest of the numbers"
//while we consider two numbers at a time
|
Now that we have this arrangement, let's make a couple of flags that will help us keep track of whether we're ascending or descending. Now that we have two numbers isolated, we can compare them and initialize our flags appropriately.
1 2
|
bool isAscending = (nextToLastDigit < lastDigit);
bool isDescending = (nextToLastDigit > lastDigit);
|
We have an initial snapshot of what our state looks like based on the two least-significant digits. Now we must continue through the number and see if our ascending/descending trend continues. We'll do this as long as we have more digits left to evaluate (i.e. theNum hasn't been divided all the way down to zero). To do this, we're going to throw out lastDigit, shift the nextToLastDigit into lastDigit, and get a new nextToLastDigit.
1 2 3 4 5 6 7 8
|
//at this point, theNum is 245
while(theNum != 0) //while we still have something in our "rest of the numbers"
{
lastDigit = nextToLastDigit; //move 8 into last digit
nextToLastDigit = theNum % 10; //this will be 5
theNum /= 10; //take 5 out of "the rest of the numbers", left with 24
//...
}
|
With this new digit now available to us in the variable nextToLastDigit, we can see if our current trend (whatever it is) is continuing. If we decided earlier that the first two numbers indicate we're ascending, we need to check if we're still ascending after pulling in the next digit. Same thing for descending.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
while(...)
{
//...code from previous step...
if(isAscending && !(nextToLastDigit < lastDigit)
{
//we were ascending, but doing the digit check shows that's no longer the case
isAscending = false;
break; //go ahead and break, no use checking the rest of the number
}
if(isDescending && !(nextToLastDigit > lastDigit)
{
//we were descending, but doing the digit check shows that's no longer the case
isDescending = false;
break; //go ahead and break, no use checking the rest of the number
}
}
|
By the end of this loop, we can use the flags isAscending and isDescending to decide what to tell the user.