Minimize steps to reduce integer
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithm design skills and proficiency with integer operations and decision-making under parity constraints, testing competencies such as bitwise reasoning, greedy and dynamic-programming intuition, and complexity analysis.
Constraints
- 1 <= n <= 2^61 - 1
- Each operation must be one of: divide by 2 when even, add 1 when odd, or subtract 1 when odd
Examples
Input: (1,)
Expected Output: 0
Explanation: n is already 1, so no steps are needed.
Input: (2,)
Expected Output: 1
Explanation: 2 is even, so divide by 2: 2 -> 1.
Hints
- For an odd number, compare what happens after choosing n - 1 versus n + 1. Which one creates more trailing zero bits in binary?
- There is one important exception to the n % 4 rule: handle n = 3 separately.