每日一題---數(shù)字轉換為十六進制數(shù)

數(shù)字轉換為十六進制數(shù)

給定一個整數(shù)聪黎,編寫一個算法將這個數(shù)轉換為十六進制數(shù)可都。對于負整數(shù)耕姊,我們通常使用 補碼運算 方法膀值。

注意:

  1. 十六進制中所有字母(a-f)都必須是小寫棍丐。
  2. 十六進制字符串中不能包含多余的前導零误辑。如果要轉化的數(shù)為0,那么以單個字符'0'來表示歌逢;對于其他情況巾钉,十六進制字符串中的第一個字符將不會是0字符。
  3. 給定的數(shù)確保在32位有符號整數(shù)范圍內(nèi)秘案。
  4. 不能使用任何由庫提供的將數(shù)字直接轉換或格式化為十六進制的方法砰苍。

示例1

輸入:
26

輸出:
"1a"

示例2

輸入:
-1

輸出:
"ffffffff"

本人的渣渣垃圾代碼(Java)

public class ToHex {
    public static String toHex(int num) {
        if (num >= 0) {
            return parse(num);
        }else {
            return parse((long)Math.pow(2, 32) + num);
        }
    }

    private static String parse(long num){
        char c = '0';
        StringBuilder s = new StringBuilder();
        while (num / 16 > 0) {
            c = numToChar(num);
            s.append(c);
            num = num / 16;
        }
        s.append(numToChar(num));
        return s.reverse().toString();
    }

    private static char numToChar(long num){
        char c = '0';
        if (num % 16 <= 9) {
            //利用ASCII碼
            c = (char) (c + num % 16);
        }else {
            // 'a'的ASCII碼為97,對應16進制中的10阱高,所以97 + n - 10為對應的字符的ASCII碼
            c = (char) (87 + num % 16);
        }
        return c;
    }

    public static void main(String[] args) { 
        String s = toHex(-1);
    }
}
  • 數(shù)字與字符轉換可以通過ASCII碼進行轉換赚导。數(shù)字0對應的ASCII碼值為48,字母A對應的ASCII碼為65讨惩,字母a對應的ASCII碼為97辟癌。
  • 在32位有符號整數(shù)下,0xffffffff對應的原碼與-1的補碼相同荐捻,所以使用(long)Math.pow(2, 32) + num來代替負數(shù)的補碼黍少。
  • 查看題解,本題主要考察位運算处面,對位運算還缺乏理解厂置,還需要深入學習。
優(yōu)秀位運算題解:
class Solution {
    public String toHex(int num) {
        char[] hex = "0123456789abcdef".toCharArray();
        StringBuilder str=new StringBuilder();
        while(num != 0){
            int end = num&15;//比較二進制的差異 
           //// System.out.println(end);
            str.append(hex[end]);
            //無符號右移4位
            num >>>=4;
        }
        if(str.length() == 0){
           str.append("0");
        }
        //反轉字符
        StringBuilder str0=str.reverse();

        return str0.toString();
    }
}

作者:zhu-five
鏈接:https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/solution/zi-fu-huan-chong-qu-jia-su-an-wei-bi-jiao-by-zhu-f/
來源:力扣(LeetCode)
著作權歸作者所有魂角。商業(yè)轉載請聯(lián)系作者獲得授權昵济,非商業(yè)轉載請注明出處。

對數(shù)字的每四位與15(即2進制中的1111or16進制中的f)進行與運算野揪,得出的結果就是這一位的值访忿。最后的推出條件位num = 0,即為0000時退出斯稳,數(shù)字轉換完成海铆。

以下為java源碼中IntegerToHexString()方法:

/**
 * Returns a string representation of the integer argument as an
 * unsigned integer in base&nbsp;16.
 *
 * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
 * if the argument is negative; otherwise, it is equal to the
 * argument.  This value is converted to a string of ASCII digits
 * in hexadecimal (base&nbsp;16) with no extra leading
 * {@code 0}s.
 *
 * <p>The value of the argument can be recovered from the returned
 * string {@code s} by calling {@link
 * Integer#parseUnsignedInt(String, int)
 * Integer.parseUnsignedInt(s, 16)}.
 *
 * <p>If the unsigned magnitude is zero, it is represented by a
 * single zero character {@code '0'} ({@code '\u005Cu0030'});
 * otherwise, the first character of the representation of the
 * unsigned magnitude will not be the zero character. The
 * following characters are used as hexadecimal digits:
 *
 * <blockquote>
 *  {@code 0123456789abcdef}
 * </blockquote>
 *
 * These are the characters {@code '\u005Cu0030'} through
 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 * {@code '\u005Cu0066'}. If uppercase letters are
 * desired, the {@link java.lang.String#toUpperCase()} method may
 * be called on the result:
 *
 * <blockquote>
 *  {@code Integer.toHexString(n).toUpperCase()}
 * </blockquote>
 * @param   i   an integer to be converted to a string.
 * @return  the string representation of the unsigned integer value
 *          represented by the argument in hexadecimal (base&nbsp;16).
 * @see #parseUnsignedInt(String, int)
 * @see #toUnsignedString(int, int)
 * @since   JDK1.0.2
 */
public static String toHexString(int i) {
  return toUnsignedString0(i, 4);
}
/**
 * Convert the integer to an unsigned number.
 */
private static String toUnsignedString0(int val, int shift) {
    // assert shift > 0 && shift <=5 : "Illegal shift value";
    int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
    int chars = Math.max(((mag + (shift - 1)) / shift), 1);
    char[] buf = new char[chars];

    formatUnsignedInt(val, shift, buf, 0, chars);

    // Use special constructor which takes over "buf".
    return new String(buf, true);
}

java源代碼中也基本是這種思想。我們需要從源碼中學習的還有很多挣惰。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末卧斟,一起剝皮案震驚了整個濱河市翁都,隨后出現(xiàn)的幾起案子鸦难,更是在濱河造成了極大的恐慌,老刑警劉巖集漾,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竖幔,死亡現(xiàn)場離奇詭異板乙,居然都是意外死亡,警方通過查閱死者的電腦和手機拳氢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門亡驰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來晓猛,“玉大人饿幅,你說我怎么就攤上這事凡辱。” “怎么了栗恩?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵透乾,是天一觀的道長。 經(jīng)常有香客問我磕秤,道長乳乌,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任市咆,我火速辦了婚禮汉操,結果婚禮上,老公的妹妹穿的比我還像新娘蒙兰。我一直安慰自己磷瘤,他們只是感情好,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布搜变。 她就那樣靜靜地躺著采缚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪挠他。 梳的紋絲不亂的頭發(fā)上扳抽,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音殖侵,去河邊找鬼贸呢。 笑死,一個胖子當著我的面吹牛拢军,可吹牛的內(nèi)容都是我干的楞陷。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼朴沿,長吁一口氣:“原來是場噩夢啊……” “哼猜谚!你這毒婦竟也來了?” 一聲冷哼從身側響起赌渣,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤魏铅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后坚芜,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體览芳,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年鸿竖,在試婚紗的時候發(fā)現(xiàn)自己被綠了沧竟。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铸敏。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖悟泵,靈堂內(nèi)的尸體忽然破棺而出杈笔,到底是詐尸還是另有隱情,我是刑警寧澤糕非,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布蒙具,位于F島的核電站,受9級特大地震影響朽肥,放射性物質發(fā)生泄漏禁筏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一衡招、第九天 我趴在偏房一處隱蔽的房頂上張望篱昔。 院中可真熱鬧,春花似錦始腾、人聲如沸州刽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽怀伦。三九已至,卻和暖如春山林,著一層夾襖步出監(jiān)牢的瞬間房待,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工驼抹, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留桑孩,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓框冀,卻偏偏與公主長得像流椒,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子明也,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354