Robert Eisele
Engineer, Systems Architect and DBA

Codefights: No odd Digits

Original Problem

Given a non-negative integer number, remove all of its odd digits (if all of the digits are removed, return zero).

  • [time limit] 4000ms (js)
  • [input] integer n
  • [output] integer

Solution

A number without all it's odd numbers is the sum of all the even numbers multiplied by a continues series of power of ten. For example the number 123456 is 6 + 10 * 4 + 100 * 2. Based on this observation, we can formulate a recursive formula:

\[f(n) = \begin{cases} f(\left\lfloor\frac{n}{10}\right\rfloor) \cdot 10 + n\bmod 10, & \text{if}\ n\text{ is even} \\ f(\left\lfloor\frac{n}{10}\right\rfloor), & \text{otherwise} \end{cases}\]

With an end-check formulated as JavaScript:

_ = noOddDigits = n =>
    n ?
       n % 2
            ? _(n / 10 | 0)
            : _(n / 10 | 0) * 10 + n % 10
      : 0

Go to overview