Q:
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:26
Output:"1a"
Example 2:
Input:-1
Output:"ffffffff"
A:
用到了mask(掩碼)拼苍,目的是在bit manipulation時可以逐個bit判斷每一位是否為1。當我們傳進來一個十進制數(shù)字,如28時,它在計算機里是用二進制表達為... 0001 1100的,當使用mask: ... 0000 1111(15)時舌狗,因為是全1,并且1111之前的數(shù)字為全0,所以不管這個數(shù)字后四位以前的bit是什么內(nèi)容缭嫡,最終對會被記作0,這也就是掩碼抬闷,掩蓋妇蛀,mask的意義。可以保證只針對最后4 bit讥耗,保留原始bit pattern輸出有勾,那么bit manipulation邏輯&后,last 4 bits輸出為1100(12)古程,我們回到之前的數(shù)組里找到index為12的值蔼卡,是“c”。再通過右移四位挣磨,扔掉1100雇逞,那么這時我們操作的4 bits對象為0001,再次使用mask 1111茁裙,便得到了0001(1)塘砸,就是“1”。
public class Solution {
char[] hexchar = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f'};
public String toHex(int num) {
if(num == 0) return "0";
String result = "";
while(num != 0){
result = hexchar[(num & 15)] + result; //15 is mask 1111 = 0b1111
num = (num >>> 4);
}
return result;
}
}
再次提一下more efficient的StringBuilder寫法:
StringBuilder sb = new StringBuilder(); while (num != 0) { sb.insert(0, hexchar[num & 15]); num = num >>> 4; } return sb.toString();
一下是test case “28”和 “-28”的實際操作過程:
Notes:
bit manipulation 位運算:
“>>” 右移,高位補符號位矾瘾,右移1位表示除2
“>>>” 無符號右移女轿,高位補0
“<<” 左移,左移1為表示乘2
| 或運算:
比較bit壕翩,有一個是1蛉迹,結(jié)果是1。
應(yīng)用:點亮某bit設(shè)置其為1放妈,void set(int)
& 與運算:
比較bit北救,當都是1時,結(jié)果是1芜抒。
應(yīng)用:檢查某bit位是否為1珍策,boolean get(int)
如果不是1,那么返回的時候是0宅倒,如果是1攘宙,返回的時候 !=0
two's complement:
12 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
---|---|---|---|---|---|---|---|---|
取反 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 1 |
補碼+1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
-12 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 |