LeetCode#405: Convert a Number to Hexadecimal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/84197151

Description

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

Example

Input:
26

Output:
"1a"
Input:
-1

Output:
"ffffffff"

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.

Solution

由于二进制转十六进制是四位四位的转换,所以将compare设为15也就是只有最低四位为1111其余都为0,将其与要转换的数字从低到高四位四位的转换并添加到字符串中。

class Solution {
	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";
        int compare = 15;	// 2^16-1: 0000...001111
        String res = "";
        while(num != 0) {
        	res = map[(compare & num)] + res;
        	num = num >>> 4;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/84197151