← Salesforce Interview Insights
My first instinct was to just loop and keep dividing by 2, which works fine but felt clunky.
Start by clarifying edge cases (e.g., zero, negative numbers) and then present a bitwise solution: a positive integer n is a power of two if and only if n > 0 and (n & (n - 1)) == 0. Explain why this works and mention the time and space complexity.
Pro tip: Mention that this bitwise trick is a common interview question and that you would also handle edge cases like n <= 0; showing awareness of integer overflow or language-specific behavior (e.g., in Python, negative numbers have infinite bits) can impress the interviewer.
Ask whether the input can be negative, zero, or non-integer, and confirm the expected return type (boolean).
Briefly mention a loop that repeatedly divides by 2, but note it's less efficient than the bitwise method.
Explain that for positive integers, n & (n - 1) clears the lowest set bit; if the result is 0 and n > 0, n is a power of two.
State that the bitwise approach runs in O(1) time and O(1) space, and explicitly handle n <= 0 by returning false.
Walk through examples like n=1 (true), n=2 (true), n=3 (false), n=0 (false), n=-4 (false) to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.