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.
High-level languages provide formatting utilities (format, Integer.toBinaryString, printf/%b) which are concise and efficient; use them when available.
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.
classSolution {
}
publicstatic String intToBin(int n, int bits) {
int mask = bits >= 32 ?-1 : ((1 << bits) - 1);
int v = n & mask;
char[] s =newchar[bits];
for (int i = 0; i < bits; ++i) s[i]= (((v >> (bits - 1 - i)) & 1) == 1) ?'1' : '0';
returnnew String(s);
}
1
2
3
4
5
6
7
8
9
10
objectSolution {
}
funintToBin(n: Int, bits: Int = 8): String {
val mask = if (bits >=32) -1else (1 shl bits) - 1val 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
classSolution:
defint_to_bin(self, n: int, bits: int =8) -> str:
mask = (1<< bits) -1 v = n & mask
return''.join('1'if (v >> i) &1else'0'for i in range(bits -1, -1, -1))