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 0
s. 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:26Output:"1a"
Example 2:
Input:-1Output:"ffffffff"
翻譯:將一個(gè)數(shù)字的位表示表示為十六進(jìn)制,注意先導(dǎo)的零是要被去掉的。
典型的位操作,以四個(gè)位為單位進(jìn)行操作取與。然后進(jìn)行位右移循環(huán)。
要值得注意的是,右移分為算術(shù)右移和邏輯右移。算數(shù)右移是在右端補(bǔ)K個(gè)0,邏輯右移是在右端補(bǔ)K個(gè)最高位符號(hào),一般語(yǔ)言的右移都是邏輯右移。對(duì)于正數(shù)來(lái)說(shuō),最高位是0,右移的結(jié)果最后總是零(因?yàn)樽罡呶簧鲜?),對(duì)于負(fù)數(shù)來(lái)說(shuō),右移的結(jié)果最后總是-1,(因?yàn)樽罡呶簧鲜?)。本來(lái)想用是否等于最后的結(jié)果(-1)來(lái)表示是否循環(huán)結(jié)束,但是這種想法是錯(cuò)誤的。例如對(duì)于一個(gè)字節(jié)的數(shù)(1111 1110) 和(1101 1110)這兩個(gè)數(shù) 前者左移四位就達(dá)到了-1,后者左移八位才到達(dá),但是取出兩者的位都需要兩次操作。
其實(shí),注意到負(fù)數(shù)最高位上是1,所以循環(huán)的次數(shù)一定是8,對(duì)于一個(gè)正數(shù)來(lái)說(shuō),其循環(huán)的次數(shù)由最高非零位來(lái)表示,于是可以由(num&mask)&&(num==0)來(lái)表示。
class Solution {
public String toHex(int num) {
StringBuilder sb = new StringBuilder();
if(num==0)
return "0";
for(int i = 0 ;i<8;i++)
{
int mask = 0x0F;
int val = num&mask;
if(val==0&&num==0)
break;
char ch;
if(val>=10)
ch=(char)('a'+val-10);
else
ch=(char)('0'+val);
sb.insert(0,ch);
num>>=4;
}
return sb.toString();
}
}