Skip to the code
cf.
+10 XP

#492 Shrink a Counter to One

easy

A notification badge shows a counter n. In one step you may subtract 1 from it, halve it if it is even, or divide it by 3 if it is a multiple of 3.

Write fewestShrinkSteps(n) that returns the fewest steps needed to bring the counter down to exactly 1.

Example 1

Input: n = 10
Output: 3

10 → 9 → 3 → 1. Halving first (10 → 5 → 4 → 2 → 1) takes 4 steps.

Example 2

Input: n = 6
Output: 2

6 → 2 → 1, or 6 → 3 → 1.

Constraints

  • 1 <= n <= 100000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).