LeetCode 405. Convert a Number to Hexadecimal (把一个数转化为16进制)

时间:2022-10-21 21:00:27

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. 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.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

题目标签:Bit Manipulation

  这道题目给了我们一个int 数字,我们需要把它转化成16进制,并且要把leading zeros都去掉。首先设立一个map把10-a, 11-b, 12-c,13-d,14-e,15-f 存入map。设一个for loop走32次, 因为16进制是4个bits为一组,所以这个loop可以设为i=i+4;然后每一次loop,需要一个进制位数,1,2,4,8, 利用num & 1把最右边的bit 拿出来 * 进制位数(1,2,4,8),再利用 >> 1 把bits往右移一位。当4格bits的总和知道以后,如果比10小,直接保存,如果大于等于10,就去map里找到对应的值存入。最后一步就是去掉leading zeros。

Java Solution:

Runtime beats 27.25%

完成日期:06/28/2017

关键词:Bit Manipulation

关键点:利用 & 1拿到bit, 利用 >> 来移动bits

 public class Solution
{
public String toHex(int num)
{
if(num == 0)
return "0"; HashMap<Integer, String> map = new HashMap<>();
StringBuilder str = new StringBuilder();
String res = ""; map.put(10, "a");
map.put(11, "b");
map.put(12, "c");
map.put(13, "d");
map.put(14, "e");
map.put(15, "f"); for(int i=0; i<31; i=i+4) // iterate 32 bits
{
int sum = 0;
for(int j=1; j<=8; j=j*2) // get 4 bits sum
{
sum += (num & 1) * j;
num = num >> 1;
} if(sum < 10)
str.insert(0, sum);
else
{
str.insert(0, map.get(sum));
}
} res = str.toString();
// get rid of leading zeros
for(int i=0; i<res.length(); i++)
{
if(res.charAt(i) != '0')
{
res = res.substring(i);
break;
}
} return res;
}
}

参考资料:

https://*.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text

LeetCode 算法题目列表 - LeetCode Algorithms Questions List