Reputation: 11
Backstory (not important to the question): I've got a question in one of my classes and I couldn't solve it for the past week, and I am just so stuck with it and trying to find a good solution for it, maybe it's just my limited thinking or being new to the whole recursion idea in general or new to learning the programming language we are working with (C language).
The problem: So our task is to build a "function" (I don't know the correct word for it) that for a given integer num:
For example: The number 343,418 will be a valid number because every digit in an odd index is odd and every digit in an even index is even.(the example + indexes)
The number 343,518 will be an invalid number because on the second index there is a number 5, even index odd number. (the example + indexes)
Any hints to a solution or a way to solve this will be greatly appreciated as I was trying to solve this for a while.
Upvotes: 0
Views: 272
Reputation: 3256
Here is a possible approach:
Since the one's (least significant) digit must be even, a valid number considered as a whole must also be even. So stop and return 0 if num % 2 != 0
.
Get the ten's digit by tens = (num / 10) % 10
, leveraging that integer division rounds down. If tens
is zero, we are done validating the digits, so return 1 if tens == 0
. Otherwise tens
must be odd, so return 0 if tens % 2 == 0
.
Now discard the bottom two digits with num /= 100
and go back to step 1.
The "go back to step 1" part could be done with a while loop or as a "tail call" if you want to express it recursively.
Upvotes: 1
Reputation: 311163
As suggested in the discussion in the comments, the idea here is to iterate over the digits and keep track of the index as you go, where in each step you compare the digit and index's evenness:
int compareDigitsToIndexes(int num) {
int ind = 0;
while (num > 0) {
int digit = num % 10;
if (ind % 2 != digit % 2) {
return 0;
}
num /= 10;
++ind;
}
return 1;
}
Upvotes: 1