Problem 542158 · easy · Level 05 Advanced Algorithms & Graphs

Which Power Is the Tile Size?

bit manipulation · powers of two

A tiling robot accepts square tiles whose side n is a power of two. Some jobs additionally need n to be a power of four. Return "four" if n is a power of four, "two" if it is a power of two but not of four, and "neither" otherwise. Solve it without loops or logarithms.

Examples

Input:  n = 64
Output: "four"
Input:  n = 32
Output: "two"
Input:  n = 0
Output: "neither"

Constraints

  • -2**63 <= n < 2**63
  • 1 counts as a power of four (4**0).
  • Target complexity: O(1).

Goals

  • Test for a power of two with n & (n - 1)
  • Distinguish powers of four by the position of the single bit
  • Reject zero and negative sizes
Starting Python…