LeetCode:405. Convert a Number to Hexadecimal

Description

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:
-1

Output:
"ffffffff"

原題鏈接405. Convert a Number to Hexadecimal

Solution

solution1

思路
最原始的方法,完全按照數字的源碼、反碼、補碼的格式來轉化,這種思路下,就要先將數字轉化爲2進制再將二進制轉化爲十六進制。同時,還需要注意數字爲負數時,需要一些特殊的操作。這種解法非常麻煩,但是卻非常直接。

代碼

public String toHex(int num) {
    if (num == 0) {
        return "0";
    }
    int MAX = 32;
    boolean isNegative = false;
    int bits[] = new int[MAX];
    if (num < 0) {
        isNegative = true;
        bits[MAX - 1] = 1;
        num = -num;
    }

    int i = 0;
    // 轉化爲二進制的原碼
    while (num > 0) {
        bits[i++] = num % 2;
        num /= 2;
    }

    // 如果是負數,需要取反並且+1從而得到補碼
    if (isNegative) {
        // 取反
        for (int j = 0; j < bits.length - 1; j++) {
            bits[j] = (bits[j] + 1) % 2;
        }
        // +1
        int digit = 1;
        int res = 0;
        for (int j = 0; j < bits.length - 1; j++) {
            res = bits[j] + digit;
            bits[j] = res % 2;
            digit = res / 2;
        }
    }

    // 二進制轉化爲十六進制
    String ret = "";
    for (int j = 0; j < bits.length; j += 4) {
        int data = 0;
        for (int j2 = 0; j2 < 4; j2++) {
            data += bits[j + j2] * (1 << j2);
        }
        ret = String.format("%x", data) + ret;
    }

    // 去掉字符串前面多餘的0
    for (int j = 0; j < ret.length(); j++) {
        if (ret.charAt(j) != '0') {
            ret = ret.substring(j);
            break;
        }
    }

    return ret;
}

solution2

思路
第二種解法就是按位與來獲取。計算機內部操作一個數字的時候其實用的就是該數字的補碼。既然是要得到十六進制,那麼每次與上0xF(二進制就是1111),得到一個值,然後數字向右移動4位。這裏需要注意的是數字是有符號的,剛好可以利用Java提供的無符號右移>>>

代碼

char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

public String toHex(int num) {
    if(num == 0) return "0";
    String result = "";
    while(num != 0){
        result = map[(num & 0xF)] + result; 
        num = (num >>> 4);
    }
    return result;
}


參考:【LeetCode】405 Convert a Number to Hexadecimal (java實現)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章