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.

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 //        每次取出最右边四位,如果其大于等于10,找到对应的字母加入结果,反之则将对应的数字加入结果,然后num像右平移四位,
 3 //        循环停止的条件是num为0,或者是已经循环了7次(java中int是32位,移了7次以后只剩4位了)
 4         String res = "", str = "0123456789abcdef";
 5         int cnt = 0;
 6         while (num != 0 && cnt++ < 8) {
 7             res = str.charAt((num & 0xf)) + res;
 8             num >>= 4;
 9         }
10         return res.isEmpty() ? "0" : res;  
11     }