您的位置:首页 > 其它

LeetCode[405] Convert a Number to Hexadecimal

2016-10-11 15:41 387 查看
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s
complement method is used.

Note:
All letters in hexadecimal (
a-f
) must be in lowercase.
The hexadecimal string must not contain extra leading 
0
s. 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.

Example 1:
Input:
26

Output:
"1a"


Example 2:
Input:
-1

Output:
"ffffffff"


不用管这个数字十进制是什么,用二进制转换为十六进制。

注意负数的情况右移位是要用符号位‘1’来补的,所以永远都不会到0,于是用一个cnt来记录移位次数(int 32bit,最多移次)

class Solution {
public:
string toHex(int num) {
string hex = "0123456789abcdef";
string ans = "";
int cnt = 0;
while (num != 0 && cnt++ < 8) {
ans.push_back(hex[num & 15]);
num >>= 4;
}
reverse(ans.begin(), ans.end());
if (ans.empty()) {
ans = "0";
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 16进制