LeetCode No.405 Convert a Number to Hexadecimal | #bit manipulation #logic and or #mask #two's complement

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。当我们传进来一个十进制数字,如28时,它在计算机里是用二进制表达为... 0001 1100的,当使用mask: ... 0000 1111(15)时,因为是全1,并且1111之前的数字为全0,所以不管这个数字后四位以前的bit是什么内容,最终对会被记作0,这也就是掩码,掩盖,mask的意义。可以保证只针对最后4 bit,保留原始bit pattern输出,那么bit manipulation逻辑&后,last 4 bits输出为1100(12),我们回到之前的数组里找到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”的实际操作过程:


LeetCode No.405 Convert a Number to Hexadecimal | #bit manipulation #logic and or #mask #two's complement_第1张图片
28,result:1c
LeetCode No.405 Convert a Number to Hexadecimal | #bit manipulation #logic and or #mask #two's complement_第2张图片
-28,result:ffffffe4

Notes:

bit manipulation 位运算
“>>” 右移,高位补符号位,右移1位表示除2
“>>>” 无符号右移,高位补0
“<<” 左移,左移1为表示乘2

| 或运算
比较bit,有一个是1,结果是1。
应用:点亮某bit设置其为1,void set(int)
& 与运算
比较bit,当都是1时,结果是1。
应用:检查某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

你可能感兴趣的:(LeetCode No.405 Convert a Number to Hexadecimal | #bit manipulation #logic and or #mask #two's complement)