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实现)

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