Problem

Convert an integer to its binary representation (as a string) using only integer/bitwise operations when possible. Support both fixed-width (e.g., 8-bit signed) and general-width encodings.

Inputs: an integer n and optionally a bits width (default 8 for byte-sized examples).

Output: a string of 0/1 characters representing the two’s-complement bit pattern of n truncated or padded to bits bits.

Examples

Example 1

1
2
Input: n = 113, bits = 8
Output: "01110001"

Example 2

1
2
Input: n = -128, bits = 8
Output: "10000000"

Notes

  • For signed values we commonly display the two’s-complement representation; for unsigned values, treat n as non-negative.

Solution

Method 1 — Built-ins / formatters

Intuition

High-level languages provide formatting utilities (format, Integer.toBinaryString, printf/%b) which are concise and efficient; use them when available.

Approach

  1. Use the language’s binary-format function to obtain a binary string for n (unsigned or signed as required).
  2. If a fixed width bits is requested, mask or pad/truncate the string to bits characters.

Code

1
2
3
4
5
6
7
8
#include <bitset>
class Solution {
 public:
  static std::string to_bin(int n, int bits = 8) {
    std::bitset<32> bs(static_cast<unsigned int>(n));
    return bs.to_string().substr(32 - bits);
  }
};
1
2
3
4
5
6
7
8
package main
import ("fmt"; "strconv")

func ToBin(n int64, bits int) string {
  s := strconv.FormatInt(n & ((1<<bits)-1), 2)
  for len(s) < bits { s = "0" + s }
  return s
}
1
2
3
4
5
6
class Solution {
  public static String toBin(int n, int bits) {
    String s = Integer.toBinaryString(n & ((1 << bits) - 1));
    return String.format("%" + bits + "s", s).replace(' ', '0');
  }
}
1
2
3
4
5
6
object Solution {
  fun toBin(n: Int, bits: Int = 8): String {
    val s = Integer.toBinaryString(n and ((1 shl bits) - 1))
    return s.padStart(bits, '0')
  }
}
1
2
3
4
5
class Solution:
  def to_bin(self, n: int, bits: int = 8) -> str:
    mask = (1 << bits) - 1
    s = format(n & mask, 'b')
    return s.rjust(bits, '0')
1
2
3
4
5
6
7
pub struct Solution;
impl Solution {
  pub fn to_bin(n: i32, bits: usize) -> String {
    let mask = ((1u64 << bits) - 1) as i64;
    format!("{:b}", (n as i64 & mask as i64)).chars().rev().collect::<String>().chars().rev().collect()
  }
}

Complexity

  • ⏰ Time complexity: O(bits) to format and possibly pad/truncate.
  • 🧺 Space complexity: O(bits) for the output string.

Method 2 — Manual bitwise construction

Intuition

Extract bits from least-significant to most-significant using bitwise AND and right-shift operations, assembling characters into a buffer. For two’s-complement signed values, mask with ((1 << bits) - 1) to get the low bits bits.

Approach

  1. Compute mask = (1 << bits) - 1 (use unsigned/wider type if bits equals word size).
  2. For i from bits-1 down to 0:
    • Compute bit = (n >> i) & 1 (ensure arithmetic vs logical right-shift semantics for negatives — masking first is safest: ((n & mask) >> i) & 1).
    • Append '1' or '0' accordingly.
  3. Return the assembled string.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
};

static std::string int_to_bin(int n, int bits = 8) {
  unsigned int mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
  unsigned int v = static_cast<unsigned int>(n) & mask;
  std::string s(bits, '0');
  for (int i = bits - 1; i >= 0; --i) { s[bits - 1 - i] = ((v >> i) & 1) ? '1' : '0'; }
  return s;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main
import "fmt"

func IntToBin(n int64, bits int) string {
  var mask uint64 = (1<<bits) - 1
  v := uint64(n) & mask
  s := make([]byte, bits)
  for i := 0; i < bits; i++ { if (v>>(bits-1-i))&1 == 1 { s[i] = '1' } else { s[i] = '0' } }
  return string(s)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
}

public static String intToBin(int n, int bits) {
  int mask = bits >= 32 ? -1 : ((1 << bits) - 1);
  int v = n & mask;
  char[] s = new char[bits];
  for (int i = 0; i < bits; ++i) s[i] = (((v >> (bits - 1 - i)) & 1) == 1) ? '1' : '0';
  return new String(s);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
object Solution {
}

fun intToBin(n: Int, bits: Int = 8): String {
  val mask = if (bits >= 32) -1 else (1 shl bits) - 1
  val v = n and mask
  val sb = StringBuilder(bits)
  for (i in bits - 1 downTo 0) sb.append(if ((v shr i) and 1 == 1) '1' else '0')
  return sb.toString()
}
1
2
3
4
5
class Solution:
  def int_to_bin(self, n: int, bits: int = 8) -> str:
    mask = (1 << bits) - 1
    v = n & mask
    return ''.join('1' if (v >> i) & 1 else '0' for i in range(bits - 1, -1, -1))
1
2
3
4
5
6
7
8
9
pub struct Solution;
impl Solution {
}

pub fn int_to_bin(n: i32, bits: usize) -> String {
  let mask = if bits >= 32 { u32::MAX } else { (1u32 << bits) - 1 };
  let v = (n as u32) & mask;
  (0..bits).rev().map(|i| if ((v >> i) & 1) == 1 { '1' } else { '0' }).collect()
}

Complexity

  • ⏰ Time complexity: O(bits) — iterate once per bit.
  • 🧺 Space complexity: O(bits) for the output string.