十進(jìn)制轉(zhuǎn)十六進(jìn)制。
除了0,首位都不為0;字母全部小寫;num可能為負(fù)數(shù)。
題目:405. Convert a Number to Hexadecimal
另外二進(jìn)制位運(yùn)算加法 題目: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"
二進(jìn)制,計(jì)算每四位得到一個十六進(jìn)制的位。
需要注意,因?yàn)榭赡転樨?fù)數(shù),所以用>>>:
位運(yùn)算符
“>>” 右移,高位補(bǔ)符號位,右移1位表示除2 (若值為正,則在高位插入0;若值為負(fù),則在高位插入1)
“>>>” 無符號右移,高位補(bǔ)0(Java獨(dú)有,無論正負(fù),都在高位插入0)
“<<” 左移,左移1為表示乘2
負(fù)數(shù)的補(bǔ)碼表示:
正數(shù)的補(bǔ)碼與原碼相同,負(fù)數(shù)的補(bǔ)碼為對該數(shù)的原碼除符號位外各位取反,然后在最后一位加1.
-5 在計(jì)算機(jī)中表達(dá)為:11111111 11111111 11111111 11111011。轉(zhuǎn)換為十六進(jìn)制: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;
}
}