Convert a Number to Hexadecimal

🏠 ⬅️ ➑️

Given an 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 - 1

Note: This problem is from LeetCode.
❌ Compiled
❌ Executed
❌ Correct
program main
    implicit none

    integer :: num
    character(len=10) :: str

    num = 26
    call get_hex_str(num, str)
    print '(A)', trim(adjustl(str))

    num = -1
    call get_hex_str(num, str)
    print '(A)', trim(adjustl(str))

contains

    subroutine get_hex_str(num, str)
        implicit none
        integer, intent(in) :: num
        character(len=*), intent(out) :: str
        integer :: i, j, k, n

        if (num < 0) then
            ! Use two's complement method
            n = abs(num) + 1
            do i = 1, 8
                k = mod(n, 16)
                select case (k)
                    case (0:9)
                        str(i:i) = char(iachar('0') + k)
                    case default
                        str(i:i) = char(iachar('a') + k - 10)
                end select
                n = n / 16
            end do
        else
            ! Positive number
            do i = 1, 8
                k = mod(num, 16)
                select case (k)
                    case (0:9)
                        str(i:i) = char(iachar('0') + k)
                    case default
                        str(i:i) = char(iachar('a') + k - 10)
                end select
                num = num / 16
            end do
        end if

        ! Reverse the string
        do i = 1, 4
            j = mod(i, 5)
            k = mod(j+1, 5)
            str(i:i) = str(k:k)
        end do

    end subroutine get_hex_str

end program main
❌ Compiled
❌ Executed
❌ Correct
```
program hexadecimal
    implicit none
    integer :: num
    character(len=100) :: hex
    character(len=16) :: digits = "0123456789abcdef"

    read(*,*) num

    if (num < 0) then
        num = not(num) + 1
    end if

    do while (num > 0)
        hex = digits(mod(num, 16) + 1) // hex
        num = num / 16
    end do

    if (hex == "") then
        hex = "0"
    end if

    write(*,*) hex
end program hexadecimal
```
🌐 Data from online sources
def to_hex(num: int) -> str:
    if num == 0:
        return '0'
    hex_str = ''
    hex_digits = '0123456789abcdef'
    n = num & 0xffffffff
    while n:
        hex_str = hex_digits[n & 0xf] + hex_str
        n >>= 4
    return hex_str

The algorithm for converting an integer to its hexadecimal representation follows these steps:

  1. Check if the input number is 0, if so, return the string "0".
  2. Initialize an empty string (hex) to store the hexadecimal representation of the integer.
  3. Initialize an array or string (hexDigits) containing the characters representing the hexadecimal digits from 0 to 15 (0-9 and a-f).
  4. If the input integer is negative, convert it to its unsigned 32-bit integer representation.
  5. While the integer is not 0, extract the last 4 bits using a bitwise AND operation with the value 0xf (15 in decimal) and use the result as an index to get the corresponding hexadecimal character from hexDigits. Append this character to the left side of the hex string.
  6. Shift the integer right by 4 bits (n >>= 4) to move on to the next 4 bits.
  7. Repeat steps 5 and 6 until the integer is 0.
  8. Return the hex string as the final hexadecimal representation of the input integer.
🌐 Data from online sources
std::string toHex(int num) {
    if (num == 0) return "0";
    std::string hex = "";
    unsigned int n = num;
    char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    while (n) {
        hex = hexDigits[n & 15] + hex;
        n >>= 4;
    }
    return hex;
}

The algorithm for converting an integer to its hexadecimal representation follows these steps:

  1. Check if the input number is 0, if so, return the string "0".
  2. Initialize an empty string (hex) to store the hexadecimal representation of the integer.
  3. Initialize an array or string (hexDigits) containing the characters representing the hexadecimal digits from 0 to 15 (0-9 and a-f).
  4. If the input integer is negative, convert it to its unsigned 32-bit integer representation.
  5. While the integer is not 0, extract the last 4 bits using a bitwise AND operation with the value 0xf (15 in decimal) and use the result as an index to get the corresponding hexadecimal character from hexDigits. Append this character to the left side of the hex string.
  6. Shift the integer right by 4 bits (n >>= 4) to move on to the next 4 bits.
  7. Repeat steps 5 and 6 until the integer is 0.
  8. Return the hex string as the final hexadecimal representation of the input integer.