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”的实际操作过程:


28,result:1c
-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的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 2017/9/11 啾啾说:“给熟人立规矩…” 我怎么如此的幸运呢? 1.早起,洗了澡,月亮日没吃什么东西,本来打...
    扶摇万事屋阅读 176评论 0 1
  • 上了大学后,就很少再去看高中时看过的书了 ,高中时,每天看点儿书,即便没有手机,每天也是很开心的,大学了,明明身边...
    风中的风铃草阅读 163评论 0 0
  • 喜欢这个最漂亮最恢宏的名字。安放唇齿之间,仿佛看见不断前行又不断回返的时间,温柔醇厚又严洌地回旋向上,拧着螺丝劲一...
    铭玥咏全阅读 204评论 0 0
  • 说出来你可能不信,我最近在追一部年代剧。 故事的背景是在改革年代,主人公是一个孤儿和一个弃婴,初相识的时候,男主角...
    延边阅读 780评论 1 2