Skip to main content
Back to problems
#405
Easy Algorithms

Convert a number to hexadecimal

Math String Bit Manipulation
53.3% acceptance
Jan 13, 2026
1436
229
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn to_hex(num: i32) -> String {
    if num == 0 {
      return "0".to_string();
    }
    
    let mut num = num as u32;
    let mut result = String::new();
    let hex_chars = b"0123456789abcdef";
    
    while num > 0 {
      result.push(hex_chars[(num & 0xf) as usize] as char);
      num >>= 4;
    }
    
    result.chars().rev().collect()
  }
}