Show problems as
Classic problem #326EasyMathRecursion

Power of Three

Real-world version: Proving Cabinet Batch Sizes
Tracked in this browser only
Read Power of Three on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A sourdough bakery opens with a single loaf in the proving cabinet on its first day, and every day after that it trebles what the cabinet held the day before: one loaf, then three, then nine, then twenty-seven, and onward with no ceiling.

A stocktaker hands you one figure n copied out of the order book by hand. Return true when n is exactly the number of loaves the cabinet held on some day, and false otherwise.

Because the figure is copied by hand it may arrive as zero or as a negative number. The cabinet was never empty and never held a negative number of loaves, so such a figure is not a batch size.

Examples

Example 1

Input
n = 81
Output
true

The cabinet held eighty-one loaves four days after the first, so the figure matches a day's contents.

Example 2

Input
n = 6
Output
false

Six sits between the batches of three and nine, so no day's cabinet held exactly six loaves.

Example 3

Input
n = 243
Output
true

Two hundred and forty-three is what the cabinet held five days after the first.

Example 4

Input
n = -9
Output
false

The figure is negative, and the cabinet never held a negative number of loaves, whatever its magnitude looks like.

Constraints

  • -2^31 <= n <= 2^31 - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def is_power_of_three(n: int) -> bool:
Java
public boolean isPowerOfThree(int n)