Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Check whether a number is a power of four with bit tricks.
Problem: Check whether a number is a power of four with bit tricks.
def p4(n):
return n > 0 and n & (n - 1) == 0 and n & 0x55555555 != 0
print([p4(x) for x in (16, 32, 64, 1, 0)])What is printed?- A. [True, True, True, True, False]
- B. [True, False, True, False, False]
- C. [True, False, True, True, False]
- D. [True, False, True, True, True]
Correct answer: C. [True, False, True, True, False]
n & (n − 1) == 0 keeps powers of two; the mask 0x55555555 has 1s only at even bit positions (0, 2, 4, …), where powers of four live. 32 = 2⁵ has its bit at an odd position, so it fails; 1 = 4⁰ passes; 0 fails the n > 0 test.
More Coding Interview Problems questions
- Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set…
- Problem: Break n into at least two positive integers to maximise their product. python def brk(n): dp = [0, 1] + [0] (n - 1) for i in…
- A suffix array of a string of length n is built by putting all suffixes in a list and sorting them with a comparison sort, where each…
- What is the solution of T(n) = T(n/2) + T(n/4) + n?
- Edge case: Java's int arithmetic wraps around in two's complement. The Python code below emulates exactly what this Java line computes…
- Edge case: Array sorting and parseInt in JavaScript. javascript console.log([3, 20, 100].sort().join(","), [1, 2…