CasaPanacea
BAN USERWe are looking for numbers that have an even number of digits (2 digits, 4 digits etc.) and only those that have odd digits in them. This code finds 650 such numbers between 1 and 100,000. You can pass any other limit that you want:
bool isAllOddDigits(int number)
{
while (number > 0)
{
int digit = number % 10;
if ((digit % 2) == 0)
return false;
number = number / 10;
}
return true;
}
int evenNumOfOddDigits(const int & maxNumber)
{
int count = 0;
int powerOf10 = 1;
while (true)
{
// Start with 2 digit odd number (e.g. 11) then 4 digit (1001) and so on
int from = (int)pow(10, powerOf10) + 1;
if (from > maxNumber)
break;
// Go up to next power of 10
int to = (int)pow(10, powerOf10 + 1);
// From 11 to 99 then 1001 to 9999 and so on
for (int i = from; i < to; i += 2) // Skip even numbers since then have an even digit
if (isAllOddDigits(i))
count++;
powerOf10 += 2; // Skip over numbers that don't have an even number of digits
}
return count;
}
There is a simpler solution for the case of 1 to 100,000 which can be generalized. Since there are 5 odds digits (1,3,5,7,9) only, there are 25 (5 * 5) two digit numbers with odd digits. In case of 4 digit numbers there will be 625 (5 to power of 4). So the answer to this specific question can be computed simply by adding 625 + 25 which is 650. I haven't written the solution for any number, it takes a little more work, but it's a much more efficient solution.
- CasaPanacea July 13, 2015