LeetCode - Algorithms - 405. Convert a Number to Hexadecimal

Problem

405. Convert a Number to Hexadecimal

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public String toHex(int num) {
char hex[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
String hexdec_num="";
if (num==0)
return "0";
else if (num>0) {
int rem;
while(num>0)
{
rem = num%16;
hexdec_num = hex[rem] + hexdec_num;
num = num/16;
}
return hexdec_num;
}
else {
num = ~num;
String s = "";
for (int i = 0; i < 8; i++) {
int n = 15 - num % 16;
s += hex[n];
num /= 16;
}
char[] charArr = s.toCharArray();
for(int i=charArr.length-1;i>=0;i--)
hexdec_num+=charArr[i];
return hexdec_num;
}
}
}

Submission Detail

  • 100 / 100 test cases passed.
  • Runtime: 11 ms, faster than 8.70% of Java online submissions for Convert a Number to Hexadecimal.
  • Memory Usage: 37.7 MB, less than 8.33% of Java online submissions for Convert a Number to Hexadecimal.

ref