CodingEasy
Check power of 2 and define class structure
Filed under SAP
Free read 1 of 3Understand the class requirements and method signatures expected by the automated grading platform.
The question
Write a function to check whether a given integer is a power of two, and design a basic class structure as required in a timed coding assessment.
Constraints
- Input integer can be positive, negative, or zero.
- Must handle bitwise operations efficiently.
- Class structure should encapsulate data and methods cleanly.
Examples
- Input
- n = 4
- Output
- True
- Why
- 4 is 2^2, so it is a power of 2.
- Input
- n = 5
- Output
- False
- Why
- 5 is not a power of 2.
Approach
Understand the class requirements and method signatures expected by the automated grading platform.
Repeatedly divide by 2 while divisible, checking if the final quotient is 1.
Use bit manipulation: a positive integer n is a power of 2 if and only if (n & (n - 1)) == 0 and n > 0.
Input values of 0 and negative integers should immediately return False.
Solution
O(1) time, O(1) space
class PowerChecker:
def __init__(self, value: int):
self.value = value
def is_power_of_two(self) -> bool:
n = self.value
return n > 0 and (n & (n - 1)) == 0
Tips
- What they are testing: Test with 0, negative numbers, 1 (2^0), and large powers of 2.
- Common mistake: Failing to account for non-positive integers where bitwise tricks might yield unexpected results or infinite loops.
Related SAP questions
Collected from public candidate posts and coding forums. Updated Nov 2026.