LeetCode-Java-405. Convert a Number to Hexadecimal

题目

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
给一个数,写一个算法将其转化为16进制,对于负整数,使用二进制补码方式
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.
十六进制(a-f)中的所有字母必须为小写。
十六进制字符串不得包含额外的前导0。 如果数字为零,则由单个零字符“0”表示; 否则,十六进制字符串中的第一个字符将不是零字符。
保证给定数字适合32位有符号整数的范围。
您不得使用库提供的任何方法将数字直接转换/格式化为十六进制。
Example 1:

Input:
26

Output:
"1a"
Example 2:

Input:
-1

Output:
"ffffffff"

代码

class Solution {
    public String toHex(int num) {
        if(num==0)
            return "0";
        String[] map = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
        StringBuilder str = new StringBuilder();
        while(num!=0)
        {
            str.insert(0,map[(num&15)]);
            //此为无符号右移4位等于除以16
            num>>>=4;
        }
        return str.toString();
    }
}

此段代码的难点在于temp&15
其实他的含义为

15的2进制   : 1111
1 的2进制   :    1
16的2进制   :10000
17的2进制   :10001
 1&15: 1
16&15: 0
17&15: 1

可以看出15的2进制为1111任何数和它进行&运算以后都会只剩下后四位的值,而后四位2进制恰好为16进制的一位,这样每次用4位进行&运算就可以转换为16进制。

猜你喜欢

转载自blog.csdn.net/qq_38345606/article/details/81007177
今日推荐