405. Number conversion to hexadecimal number
Easy difficulty 122
Given an integer, write an algorithm to convert this number into a hexadecimal number. For negative integers, we usually use one's complement arithmetic .
note:
- All letters (
a-f
) in the hexadecimal system must be lowercase.- No extra leading zeros can be included in the hexadecimal string. If the number to be converted is 0, it
'0'
is represented by a single character ; in other cases, the first character in the hexadecimal string will not be a 0 character.- The given number is guaranteed to be in the 32-bit signed integer range.
- You cannot use any method provided by the library to directly convert or format a number to hexadecimal.
Example 1:
Input: 26 Output: "1a"Example 2:
Input: -1 Output: "ffffffff"
violence
class Solution {
public:
string toHex(int num) {
string res = "";
if(num == 0){
return "0";
}
vector<char> vec = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'
};
unsigned int n = num;
while(n != 0){
string tmp(1, vec[n%16]);
res = tmp + res;
n /= 16;
}
return res;
}
};