Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows.
Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows.
int a = -16; System.out.println((a >> 2) + " " + (a >>> 28) + " " + (1 << 31));What does this print?
- A. 1073741820 15 -2147483648
- B. -4 15 2147483648
- C. -4 15 -2147483648
- D. -4 268435455 2147483648
Correct answer: C. -4 15 -2147483648
−16 is 0xFFFFFFF0. >> 2 copies the sign bit → −4 (division by 4 rounding down). >>> 28 shifts in zeros, leaving the top 4 bits 1111 = 15. 1 << 31 sets the sign bit of a 32-bit int → −2147483648; Java int cannot hold +2³¹. (Verified with a 32-bit JavaScript port, which uses the same shift semantics.)
More Coding Interview Problems questions
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '' + text to…
- Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together…
- Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it…
- Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros…
- Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros…
- Problem: Minimum single-bit flips in a and b so that (a OR b) == c. python def minflips(a, b, c): flips = 0 while a or b or c: x, y, z = a…