↓ Skip to main content
LeetCode 405: Convert a Number to Hexadecimal

LeetCode 405: Convert a Number to Hexadecimal

·277 words·2 mins· loading · loading ·
Author
Dawn Magnet
Tech enthusiast & daily solver.

Given an integer, write an algorithm to convert it to a hexadecimal number. For negative integers, we normally use two's-complement arithmetic.

Note:

  1. All letters (a-f) in the hexadecimal representation must be lowercase.
  2. The hexadecimal string must not contain unnecessary leading zeroes. If the number to convert is 0, represent it with the single character '0'; otherwise, the first character of the hexadecimal string must not be 0. 
  3. The given number is guaranteed to be within the range of a 32-bit signed integer.
  4. You may not use any library-provided method that directly converts or formats a number as hexadecimal.

Example 1:

Input:
26

Output:
"1a"

Example 2:

Input:
-1

Output:
"ffffffff"

Analysis
#

This is essentially a binary-to-hexadecimal conversion. It is best to use bitwise operations, which make efficient use of the computer’s binary architecture.

One hexadecimal digit corresponds to four binary digits.

Rust Code
#

impl Solution {
    pub fn to_hex(num: i32) -> String {
        let turned: Vec<char> = "0123456789abcdef".chars().collect();
        let mut num = num as u32;
        if num == 0 {
            return "0".to_string();
        }
        let mut res = vec![];
        while num != 0 {
            let mut tmp = 0;
            for i in 0..4 {
                tmp += (num & 1) * (1 << i);
                num >>= 1;
            }
            res.push(turned[tmp as usize]);
        }
        res.reverse();
        res.iter().collect()
    }
}

C++ Code
#

static const char * turned = "0123456789abcdef";
class Solution {
public:
    string toHex(unsigned int num) {
        string res;
        do {
            int tmp = 0;
            for (int i = 0; i < 4; ++i) {
                tmp += (num & 1) * (1 << i);
                num >>= 1;
            }
            res.push_back(turned[tmp]);
        } while (num != 0);
        reverse(res.begin(), res.end());
        return res;
    }
};