Swap Adjacent Nibble Pairs in a 32-Bit Unsigned Integer
Company: Arista Networks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: A bit manipulation problem: given a 32-bit unsigned integer, swap each even-position nibble, one hexadecimal digit of 4 bits, with the adjacent odd-position nibble and return the result. It tests masks, shifts and handling values above the signed 32-bit range.
Read the full Arista Networks Software Engineer interview experience this question came from
Constraints
- 0 <= x <= 2^32 - 1, that is, 0 <= x <= 4294967295
- x is treated as exactly 32 bits (8 nibbles), so leading zero nibbles take part in the swap
- Inputs and outputs can exceed 2^31 - 1 = 2147483647: Java uses long and C++ uses long long; all values stay below 2^53
Examples
Input: (0,)
Expected Output: 0
Explanation: Minimum value: all eight nibbles are zero, so swapping changes nothing.
Input: (1,)
Expected Output: 16
Explanation: 0x00000001 becomes 0x00000010: the leading-zero nibble 1 swaps in with nibble 0.
Hints
- Number the eight nibbles 0 to 7 from the least significant end; each even position trades places with the odd position directly above it.
- Leading zero nibbles still count: picture x as always having exactly eight hexadecimal digits.
- The result can be as large as 4294967295, so make sure your return type and intermediate values cannot overflow or turn negative.