LeetCode 0405. Convert a Number to Hexadecimal Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0405. Convert a Number to Hexadecimal

Description

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

Solutions

Solution 1

PythonJavaC++Go
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)(code-box)

Solution 2

Java
class Solution { public String toHex(int num) { if (num == 0) { return "0"; } StringBuilder sb = new StringBuilder(); for (int i = 7; i >= 0; --i) { int x = (num >> (4 * i)) & 0xf; if (sb.length() > 0 || x != 0) { char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); sb.append(c); } } return sb.toString(); } }(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !