[位運(yùn)算]405. Convert a Number to Hexadecimal

十進(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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,899評論 0 33
  • 一、二進(jìn)制:所謂二進(jìn)制就是逢二進(jìn)一 (0,1), 因?yàn)槭褂枚M(jìn)制只有 0, 1 兩個數(shù),簡單,易于電子方式實(shí)現(xiàn) ...
    hello大象閱讀 3,612評論 0 1
  • 二進(jìn)制轉(zhuǎn)十進(jìn)制 0011 10012^(6-1) + 2^(5-1) + 2^(4-1) + 2^(1-1) = ...
    u14e閱讀 1,403評論 0 1
  • Locks:1.Table Lock:that maybe lock all table.you can usin...
    perryn閱讀 307評論 0 0
  • 現(xiàn)在特別的想睡著 眼睛特別的癢 天氣也很熱 一直在流汗也在流眼淚 我有很多話 可我真的很懶 懶到不說 我毒舌腹黑冷...
    沒有秘密的人不可愛閱讀 144評論 0 0

友情鏈接更多精彩內(nèi)容