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 | public class Solution { |