Skip to content

Commit 96f4e56

Browse files
committed
we & with 15 to get hexadecimal
1 parent bfda77b commit 96f4e56

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

bit_manipulation/toHex.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)