-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertANumberToHexadecimal.java
77 lines (62 loc) · 2.06 KB
/
ConvertANumberToHexadecimal.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package bit_manipulation.easy;
/***
* Problem 405 in Leetcode: https://leetcode.com/problems/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"
*/
public class ConvertANumberToHexadecimal {
private static final char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static void main(String[] args) {
int num = -1;
System.out.println("Brute Force: " + convertIntoHexadecimalBruteForce(num));
System.out.println("Bitwise: " + convertIntoHexadecimalBitwise(num));
}
private static String convertIntoHexadecimalBruteForce(int num) {
if (num == 0) {
return "0";
}
boolean isNegative = num < 0;
num = isNegative ? (num + 1) * -1 : num;
StringBuilder sb = new StringBuilder();
while (num > 0) {
int r = num % 16;
if (isNegative) {
r = 15 - r;
}
char c = (char) (r < 10 ? r + '0' : r - 10 + 'a');
sb.append(c);
num /= 16;
}
if (isNegative) {
while (sb.length() < 8) {
sb.append('f');
}
}
return sb.reverse().toString();
}
private static String convertIntoHexadecimalBitwise(int num) {
if (num == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
while (num != 0) {
int mask = 15;
result.append(chars[(num & mask)]);
num >>>= 4;
}
return result.reverse().toString();
}
}