Problem

Given a single byte (8-bit unsigned integer) x, swap its two nibbles and return the resulting byte. A nibble is 4 bits: the low nibble (bits 0–3) and the high nibble (bits 4–7).

Example

1
2
3
Input: x = 0x34  # binary 0011 0100
Output: 0x43     # binary 0100 0011
Explanation: low nibble 0x4 and high nibble 0x3 are swapped.

Solution

Method 1 — Mask and shift (clear and combine)

Intuition

The byte consists of a high nibble (bits 4..7) and a low nibble (bits 0..3). Extract each nibble using masks, shift them to the opposite position and combine with bitwise OR.

Approach

  • Compute low = x & 0x0F and high = x & 0xF0.
  • Shift low left by 4 and high right by 4.
  • Combine: result = (low << 4) | (high >> 4) and mask with 0xFF if desired.
  • Return result.

Edge cases:

  • Input may be presented as a signed char in some languages; mask to 0xFF before bit operations to avoid sign-extension.

Code

1
2
3
4
5
6
7
8
class Solution {
 public:
  unsigned char swapNibbles(unsigned char x) {
    unsigned char low = x & 0x0F;
    unsigned char high = x & 0xF0;
    return (unsigned char)((low << 4) | (high >> 4));
  }
};
1
2
3
4
5
6
7
package main

func swapNibbles(x uint8) uint8 {
    low := x & 0x0F
    high := x & 0xF0
    return (low << 4) | (high >> 4)
}
1
2
3
4
5
6
7
8
class Solution {
  public byte swapNibbles(byte x) {
    int ux = x & 0xFF;
    int low = ux & 0x0F;
    int high = ux & 0xF0;
    return (byte)((low << 4) | (high >> 4));
  }
}
1
2
3
4
5
6
class Solution:
    def swap_nibbles(self, x: int) -> int:
        x &= 0xFF
        low = x & 0x0F
        high = x & 0xF0
        return ((low << 4) | (high >> 4)) & 0xFF

Complexity

  • ⏰ Time complexity: O(1), constant number of bit operations.
  • 🧺 Space complexity: O(1).

Method 2 — Shift and mask one-liner (alternate)

Intuition

Swapping nibbles can be done directly by shifting the whole byte left and right and masking the results to ensure only nibble bits move into place.

Approach

  • Compute ((x << 4) & 0xF0) | ((x >> 4) & 0x0F).

Code

1
2
3
4
5
6
class Solution {
 public:
  unsigned char swapNibblesFast(unsigned char x) {
    return (unsigned char)(((x << 4) & 0xF0) | ((x >> 4) & 0x0F));
  }
};
1
2
3
4
5
package main

func swapNibblesFast(x uint8) uint8 {
    return ((x << 4) & 0xF0) | ((x >> 4) & 0x0F)
}
1
2
3
4
5
6
class Solution {
  public byte swapNibblesFast(byte x) {
    int ux = x & 0xFF;
    return (byte)(((ux << 4) & 0xF0) | ((ux >> 4) & 0x0F));
  }
}
1
2
3
4
class Solution:
    def swap_nibbles_fast(self, x: int) -> int:
        x &= 0xFF
        return (((x << 4) & 0xF0) | ((x >> 4) & 0x0F)) & 0xFF

Complexity

  • ⏰ Time complexity: O(1).
  • 🧺 Space complexity: O(1).

Notes

  • This problem is a small bit-manipulation primitive commonly used in low-level code and interviews. There is no exact direct LeetCode problem with this exact title, but the operation is a standard bit trick.
  • Original reference retained in source_links.