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"
翻譯:將一個數(shù)字的位表示表示為十六進制,注意先導的零是要被去掉的。
典型的位操作倦逐,以四個位為單位進行操作取與葡盗。然后進行位右移循環(huán)。
要值得注意的是鹰贵,右移分為算術(shù)右移和邏輯右移。算數(shù)右移是在右端補K個0,邏輯右移是在右端補K個最高位符號蝗岖,一般語言的右移都是邏輯右移。對于正數(shù)來說榔至,最高位是0抵赢,右移的結(jié)果最后總是零(因為最高位上是0),對于負數(shù)來說唧取,右移的結(jié)果最后總是-1,(因為最高位上是1)铅鲤。本來想用是否等于最后的結(jié)果(-1)來表示是否循環(huán)結(jié)束,但是這種想法是錯誤的枫弟。例如對于一個字節(jié)的數(shù)(1111 1110) 和(1101 1110)這兩個數(shù) 前者左移四位就達到了-1邢享,后者左移八位才到達,但是取出兩者的位都需要兩次操作淡诗。
其實骇塘,注意到負數(shù)最高位上是1,所以循環(huán)的次數(shù)一定是8韩容,對于一個正數(shù)來說款违,其循環(huán)的次數(shù)由最高非零位來表示,于是可以由(num&mask)&&(num==0)來表示宙攻。
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();
}
}