Convert a Number to Hexadecimal

Description

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 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.

Method

正数转换的时候直接除以16求余数就行,负数的时候比较麻烦,直接运算的话需要和正数分开处理。一种方法是将正数和负数转换成同一种形式。下面的方法可以将有符号正数转换成无符号long。

1
long n = num & 0x00000000ffffffffL;

Solution

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public String toHex(int num) {
long n = num & 0x00000000ffffffffL;
StringBuilder sb = new StringBuilder();
char[] map = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
while(n > 0){
sb.insert(0, map[(int)(n%16)]);
n = n/16;
}
return num == 0 ? "0" : sb.toString();
}
}