I succeeded in converting a C# sharp function to C++ and the code executed successfully. I however can't seem to understand and explain the block of code below especially the initialization of 'a' and 'n' and also the nested if constructs.
int isEvens(int n)
{
int a = n % 10;
n = n / 10;
if (a == 0 || a == 2 || a == 4 || a == 6 || a == 8)
{
if (n == 0)
{
return 1;
}
else
{
return isEvens(n);
}
}
else
{
return 0;
int isEvens(int n)
{
int a = n % 10;
n = n / 10;
if (a == 0 || a == 2 || a == 4 || a == 6 || a == 8)
{
if (n == 0)
{
return 1;
}
else
{
return isEvens(n);
}
}
else
{
return 0;
}
}
int isEvens(int n)
{
int a = n % 10;
n = n / 10;
if (a == 0 || a == 2 || a == 4 || a == 6 || a == 8) {
if (n == 0) {
return 1;
} else {
return isEvens(n);
}
} else {
return 0;
}
}
> int a = n % 10;
> n = n / 10;
Well if your input number is 1234, then a is 4, and n becomes 123.
Recall that in C, integer division truncates towards zero.
The recursive function is basically examining each digit of your number.
bool isAllEven( int n )
{
constint last = n % 10;
constint rest = n / 10;
if ( last % 2 ) {
// digit is odd
returnfalse;
} else {
// is even
if ( rest == 0 ) {
// ... and the "first" digit
returntrue;
} else {
return isAllEven( rest );
}
}
}
1 2 3 4 5 6 7 8 9 10 11
bool isAllEven( int n )
{
while ( n ) {
constint last = n % 10;
if ( last % 2 ) {
returnfalse;
}
n = n / 10;
}
returntrue;
}