Code Lab

Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado

Power of three

FácilBasics10 min

Write a function isPowerOfThree(n) that returns true if n is a power of 3 and false if it is not.

  • Powers of 3 are 1, 3, 9, 27, 81, .... 1 counts: it is 3 to the power 0.
  • n is an integer from -2000000000 to 2000000000. 0 and negative numbers are not powers of 3.
  • 6 and 45 divide by 3 with no remainder, but they are not powers of 3.

Then write a second function isPowerOf(n, base): the same check for any base. The parameter base is an integer, 2 or more. isPowerOf(16, 2) is true because 16 = 2 * 2 * 2 * 2. The same rules apply: 1 counts for every base, 0 and negative numbers never count. isPowerOfThree can just call isPowerOf(n, 3).

Both functions must be fast: big numbers are tested too, and a loop that repeats up to n times can be too slow.

In the real interview these rules were not in the task. The candidate had to ask about 1, 0 and negative numbers before coding, did not ask, and thinks this is why the interview failed.

Ejemplos

isPowerOfThree(27)

Devuelve true

27 is `3 * 3 * 3`.
isPowerOfThree(45)

Devuelve false

45 divides by 3, but it is not a power of 3.
isPowerOf(16, 2)

Devuelve true

Preguntada en Hulu · Fuente

Cargando el editor…
  1. EntradaisPowerOfThree(27)
    Esperadotrue
  2. EntradaisPowerOfThree(45)
    Esperadofalse
  3. EntradaisPowerOfThree(1)
    Esperadotrue
  4. isPowerOf(16, 2) is true, isPowerOf(12, 2) is false
  5. EntradaisPowerOfThree(0)
    Esperadofalse

Las pruebas ocultas se ejecutan al enviar