[leetcode] 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.

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.

Example 1:

Input:
26

Output:
"1a"

Example 2:

Input:
-1

Output:
"ffffffff"

分析:题目翻译一下:要求把十进制数转变成十六进制数。

对于正数,很好处理,对正数不断的除以16,将余数不断的加到结果中就可以了。代码如下:

 1 public String toHex(int num) {
 2         if ( num == 0 ) return "0";
 3         StringBuffer res = new StringBuffer();
 4         Map<Integer,Character> map = new HashMap<>();
 5         map.put(10,'a');
 6         map.put(11,'b');
 7         map.put(12,'c');
 8         map.put(13,'d');
 9         map.put(14,'e');
10         map.put(15,'f');
11         if ( num > 0 ){
12             while ( num > 0 ){
13                 int t = num % 16;
14                 if ( t >= 10 ) res.append(map.get(t));
15                 else res.append(t);
16                 num /= 16;
17             }
18         }
19         return res.reverse().toString();
20     }

但是这个方法只能处理正数。对于负数,首先我们来分析一下,负数存储的的方式是补码,比如-5:

5的原码:00000000 00000000 00000000 00000101

按位取反:11111111 11111111 11111111 11111010

末位 + 1 = 11111111 11111111 11111111 11111010 + 1 = 11111111 11111111 11111111 11111011

也就是负数的存储方式是按位取反,末位加一。

对于取反,比如~5 = -5-1,即~x = -x - 1。

思考了一下,这条路不太能走得通,因为我们相当于要拿到11111111 11111111 11111111 11111011对应的无符号整数的值,不太好搞。

 

思路二:因为无论什么类型的数字,存在内存里都是以二进制存的,那么我们是否可以从根本上实现转换呢?

16进制是每四位一个数出来,那么就按照四位生成一个。

 1 class Solution {
 2     public String toHex(int num) {
 3         if ( num == 0 ) return "0";
 4         String res = "";
 5         char[] map = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
 6         while (num != 0){
 7             int last = num & 0xF;
 8             res = map[last] + res;
 9             num>>>=4;
10         }
11         return res;
12     }
13 }

  注意这里的关键;>>>代表无符号右移,忽略符号位。

 

posted @ 2018-10-16 19:41  Lin.B  阅读(173)  评论(0编辑  收藏  举报