【LeetCode】405 Convert a Number to Hexadecimal (java实现)

来源:互联网 发布:java listfiles 排序 编辑:程序博客网 时间:2024/06/01 09:08

原题链接

https://leetcode.com/problems/convert-a-number-to-hexadecimal/

原题

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:
1. All letters in hexadecimal (a-f) must be in lowercase.
2. 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.
3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
4. 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"

题目要求

题目叫“将数字转化为十六进制”,顾名思义,这里需要注意的是数字是包含负数的,所以如果方法不很合适,处理起来会稍微麻烦一些。
要求:
1. 转化后的十六进制字符串都是小写的;
2. 十六进制字符串不能以0开头(如果只有一个0除外);
3. 数字大小在32bit范围内,不用担心处理数据时溢出;
4. 不能使用库里的转化和格式打印;

解法

解法一:最原始的方法,完全按照数字的源码、反码、补码的格式来转化,这种思路下,就要先将数字转化为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;}

解法二:第二种解法就是按位与来获取。既然是得到十六进制,那么每次与上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;}
0 0
原创粉丝点击