We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent bfda77b commit 96f4e56Copy full SHA for 96f4e56
bit_manipulation/toHex.java
@@ -0,0 +1,29 @@
1
+class Solution {
2
+ public String toHex(int num) {
3
+ /*
4
+ int has 32 bits, and we check 4 bits at a time, so we will loop 8 times.
5
+ */
6
+ if (num ==0) {
7
+ return "" + "0";
8
+ }
9
+
10
+ String map = "0123456789abcdef";
11
+ String res = "";
12
+ for (int i=0; i<8; i++) {
13
+ int ans = num&15; // 15 is 1111b , so we get hexadecimal by &
14
+ char c = map.charAt(ans);
15
+ res = c + res; // add our result
16
+ num = num >> 4; // right shift by 4, to check the next 4
17
18
+ String ret = "";
19
+ for (int i=0; i<res.length(); i++) { // we strip off any leading 0's.
20
+ if (res.charAt(i) == '0') {
21
+ continue;
22
+ } else {
23
+ ret = res.substring(i, res.length());
24
+ break;
25
26
27
+ return ret;
28
29
+}
0 commit comments