ConvertANumberToHexadecimalOPT [source code]
public class ConvertANumberToHexadecimalOPT {
static
public class Solution {
public String toHex(int num) {
char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
if (num == 0) return "0";
String rst = "";
while (num != 0) {
rst = map[(num & 0xF)] + rst;
num = (num >>> 4);
}
return rst;
}
}
public static void main(String[] args) {
ConvertANumberToHexadecimalOPT.Solution tester = new ConvertANumberToHexadecimalOPT.Solution();
int input1 = -100001;
System.out.println(Integer.toHexString(input1));
System.out.println(tester.toHex(input1));
}
}
这个是 subission 最优解:7(83).
思路还是很直接的, 就是用bit shift来做, 很聪明, 一个很简单的循环就解决了. 我确实是把问题搞复杂了, 而且对于bit manipulation 我现在确实还是有点不够熟练.
这个题目展示的一个bit技巧就是用&F这种类似的操作来提取指定位置的 bit. 这个其实以前是见过的. 一旦开窍看懂这个技巧, 这个问题的思路就简单很多了;
这个是用 StringBuilder 的版本:
public String toHex(int num) {
StringBuilder sb = new StringBuilder();
do {
int n = num & 0xf;
n += n < 0xa ? '0' : 'a' - 10;
sb.append((char)n);
} while ((num >>>= 4) != 0);
return sb.reverse().toString();
}
Problem 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.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
Difficulty:Easy
Category:Algorithms
Acceptance:40.99%
Contributor: LeetCode
Related Topics
bit manipulation