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進制轉(zhuǎn)換16進制的對照表。
把int轉(zhuǎn)換為二進制涉茧,每4位可以代表一位16進制,只需把每4位的2進制轉(zhuǎn)換為10進制,再通過對照表就可以知道每一位對應的16進制是多少。
Tips:
轉(zhuǎn)換為二進制再轉(zhuǎn)換為十進制的好處是不用考慮負數(shù)的情況酥郭,因為二進制會自動轉(zhuǎn)換為補碼。
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時停止愿吹,防止前面出現(xiàn)0
{
int sum = 0;
for(int j = 3; j >= 0; j--) //每4位2進制可以構(gòu)成一位16進制
{
sum *= 2;
if((num >> j) & 1)
sum += 1;
}
ans = table[sum] + ans; //從字符串的頭部開始加字符不从,后期不用反轉(zhuǎn)
num >>= 4;
}
return ans;
}