← Capgemini bank

Capgemini · Question 74

Power of Two

C++code⏱ O(1)💾 O(1)
Service-based

Problem

You are given integer n. Check if it is a power of two.

Approach

A power of two has exactly one bit set: n & (n-1) clears it to zero.

Time O(1)Space O(1)

How it works

  1. 1n must be strictly positive: zero, negatives and INT_MIN all return false before the bit trick runs, because a power of two can never be negative.
  2. 2Positive numbers only — n > 0 is checked first so the bit trick is never applied to a negative value like INT_MIN.
  3. 3A power of two has exactly one bit set in binary: 16 is 10000. Subtracting one flips that bit off and sets every lower bit, so 15 becomes 01111.
  4. 4ANDing the two masks clears the only set bit, so n & (n - 1) is 0 for a power of two and non-zero for anything else — one set bit clears to exactly zero.
  5. 5The same one-set-bit test detects powers of four once the set bit's position is even; counting set bits is the general version used for questions like 'power of three' as well.

Sample input / output

Input:
n = 16
Output:
true

Constraints

-2^31 <= n < 2^31.

Solution — read it, then walk it

Time O(1)Space O(1)Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
STARTinclude <iostream>using namespace stdbool isPowerOfTwo(int n)DEFINE main()cout << boolalpha <<isPowerOfTwo(16) << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/7

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits