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:
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.
You must not use any method provided by the library which converts/formats the number to hex directly.

Example:

Example 1:

Input:
26

Output:
"1a"
Example 2:

Input:
-1

Output:
"ffffffff"

Link:

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

解题方法:

先建立一个10进制转换16进制的对照表。
把int转换为二进制,每4位可以代表一位16进制,只需把每4位的2进制转换为10进制,再通过对照表就可以知道每一位对应的16进制是多少。

Tips:

转换为二进制再转换为十进制的好处是不用考虑负数的情况,因为二进制会自动转换为补码。

Time Complexity:

O(logN)

完整代码:

string toHex(int num) 
    {
        if(num == 0)
            return "0";
        string table = "0123456789abcdef";
        string ans;
        for(int i = 0; i < 8 && num != 0; i++) //每次右移4位  当num为0时停止,防止前面出现0
        {
            int sum = 0;
            for(int j = 3; j >= 0; j--) //每4位2进制可以构成一位16进制  
            {
                sum *= 2;
                if((num >> j) & 1)
                    sum += 1;
            }
            ans = table[sum] + ans;  //从字符串的头部开始加字符,后期不用反转
            num >>= 4;
        }
        return ans;     
    }

你可能感兴趣的:(Convert a Number to Hexadecimal解题报告)