Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Build confidence with an intuition-first walkthrough focused on math fundamentals.
Given a 32-bit integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
Example 1:
Input: num = 26 Output: "1a"
Example 2:
Input: num = -1 Output: "ffffffff"
Constraints:
-231 <= num <= 231 - 1Problem summary: Given a 32-bit integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Bit Manipulation
26
-1
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #405: Convert a Number to Hexadecimal
class Solution {
public String toHex(int num) {
if (num == 0) {
return "0";
}
StringBuilder sb = new StringBuilder();
while (num != 0) {
int x = num & 15;
if (x < 10) {
sb.append(x);
} else {
sb.append((char) (x - 10 + 'a'));
}
num >>>= 4;
}
return sb.reverse().toString();
}
}
// Accepted solution for LeetCode #405: Convert a Number to Hexadecimal
func toHex(num int) string {
if num == 0 {
return "0"
}
sb := &strings.Builder{}
for i := 7; i >= 0; i-- {
x := num >> (4 * i) & 0xf
if x > 0 || sb.Len() > 0 {
var c byte
if x < 10 {
c = '0' + byte(x)
} else {
c = 'a' + byte(x-10)
}
sb.WriteByte(c)
}
}
return sb.String()
}
# Accepted solution for LeetCode #405: Convert a Number to Hexadecimal
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
chars = '0123456789abcdef'
s = []
for i in range(7, -1, -1):
x = (num >> (4 * i)) & 0xF
if s or x != 0:
s.append(chars[x])
return ''.join(s)
// Accepted solution for LeetCode #405: Convert a Number to Hexadecimal
struct Solution;
#[allow(clippy::wrong_self_convention)]
impl Solution {
fn to_hex(num: i32) -> String {
format!("{:x}", num)
}
}
#[test]
fn test() {
let num = -1;
let res = "ffffffff";
assert_eq!(Solution::to_hex(num), res);
}
// Accepted solution for LeetCode #405: Convert a Number to Hexadecimal
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #405: Convert a Number to Hexadecimal
// class Solution {
// public String toHex(int num) {
// if (num == 0) {
// return "0";
// }
// StringBuilder sb = new StringBuilder();
// while (num != 0) {
// int x = num & 15;
// if (x < 10) {
// sb.append(x);
// } else {
// sb.append((char) (x - 10 + 'a'));
// }
// num >>>= 4;
// }
// return sb.reverse().toString();
// }
// }
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.