Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Check whether a number is a power of two and isolate its lowest set bit.
Problem: Check whether a number is a power of two and isolate its lowest set bit.
print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x & -x}" for x in (64, 96, 0, 1)))What is printed?- A. True 64; False 32; False 0; True 1
- B. True 64; True 32; True 0; True 1
- C. True 64; False 32; True 0; True 1
- D. True 64; False 64; False 0; True 1
Correct answer: A. True 64; False 32; False 0; True 1
x & (x − 1) clears the lowest set bit, so it is 0 only when x has a single set bit – the x > 0 guard rules out 0. x & −x isolates the lowest set bit using two's complement: 96 = 1100000₂ → 32. O(1).
More Coding Interview Problems questions
- Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space. python def single(a): ones = twos…
- Problem: Two values appear once and every other value twice. Find both (smaller first). python def twosingle(a): x = 0 for v in a: x ^= v…
- Problem: Count the bits that differ between two IDs (Hamming distance) and the total over all pairs of an array. python def ham(x, y)…
- Problem: A permissions mask is an int; report how many permissions (set bits) each mask grants. java static int popc(int x) { return…
- Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum. python a = [3, 4, 5, 6] cnt = 0 for…
- Problem: Find the missing number in an array containing n distinct values from 0..n. python def missing(a): x = len(a) for i, v in…