十进制转十六进制。
除了0,首位都不为0;字母全部小写;num可能为负数。
题目:405. Convert a Number to Hexadecimal
另外二进制位运算加法 题目:371. Sum of Two Integers
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:-1Output:"ffffffff"
二进制,计算每四位得到一个十六进制的位。
需要注意,因为可能为负数,所以用>>>:
位运算符
“>>” 右移,高位补符号位,右移1位表示除2 (若值为正,则在高位插入0;若值为负,则在高位插入1)
“>>>” 无符号右移,高位补0(Java独有,无论正负,都在高位插入0)
“<<” 左移,左移1为表示乘2
负数的补码表示:
正数的补码与原码相同,负数的补码为对该数的原码除符号位外各位取反,然后在最后一位加1.
-5 在计算机中表达为:11111111 11111111 11111111 11111011。转换为十六进制:0xFFFFFFFB。
Runtime: 9 ms
class Solution {
public String toHex(int num) {
if(num == 0) return "0";
char[] Hex = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
String res = "";
while(num != 0){
res = Hex[num & 15] + res; //15 is a mask : '1111'
num = num >>> 4;
}
return res;
}
}