LeetCode#405: Convert a Number to Hexadecimal
阿新 • • 發佈:2018-11-19
Description
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Example
Input:
26
Output:
"1a"
Input:
-1
Output:
"ffffffff"
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.
Solution
由於二進位制轉十六進位制是四位四位的轉換,所以將compare
設為15
也就是隻有最低四位為1111
其餘都為0
,將其與要轉換的數字從低到高四位四位的轉換並新增到字串中。
class Solution {
char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public String toHex(int num) {
if(num == 0) return "0";
int compare = 15; // 2^16-1: 0000...001111
String res = "";
while(num != 0) {
res = map[(compare & num)] + res;
num = num >>> 4;
}
return res;
}
}