LeetCode 405. Convert a Number to Hexadecimal (把一个数转化为16进制)
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
0
s. 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.
题目标签: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
1 public class Solution 2 { 3 public String toHex(int num) 4 { 5 if(num == 0) 6 return "0"; 7 8 HashMap<Integer, String> map = new HashMap<>(); 9 StringBuilder str = new StringBuilder(); 10 String res = ""; 11 12 map.put(10, "a"); 13 map.put(11, "b"); 14 map.put(12, "c"); 15 map.put(13, "d"); 16 map.put(14, "e"); 17 map.put(15, "f"); 18 19 for(int i=0; i<31; i=i+4) // iterate 32 bits 20 { 21 int sum = 0; 22 for(int j=1; j<=8; j=j*2) // get 4 bits sum 23 { 24 sum += (num & 1) * j; 25 num = num >> 1; 26 } 27 28 if(sum < 10) 29 str.insert(0, sum); 30 else 31 { 32 str.insert(0, map.get(sum)); 33 } 34 } 35 36 37 res = str.toString(); 38 // get rid of leading zeros 39 for(int i=0; i<res.length(); i++) 40 { 41 if(res.charAt(i) != '0') 42 { 43 res = res.substring(i); 44 break; 45 } 46 } 47 48 return res; 49 } 50 }
参考资料:
https://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text
LeetCode 算法题目列表 - LeetCode Algorithms Questions List