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 (
The hexadecimal string must not contain extra leading
zero, it is represented by a single zero 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:
Example 2:
不用管这个数字十进制是什么,用二进制转换为十六进制。
注意负数的情况右移位是要用符号位‘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;
}
};
complement method is used.
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.
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 405 Convert a Number to Hexadecimal
- LeetCode 405 Convert a Number to Hexadecimal
- LeetCode405 Convert a Number to Hexadecimal
- Leetcode 405: Convert a Number to Hexadecimal
- LeetCode405 Convert a Number to Hexadecimal
- 【LeetCode】405 Convert a Number to Hexadecimal (java实现)
- Leetcode 405 Convert a Number to Hexadecimal
- 【LeetCode】405 Convert a Number to Hexadecimal (java实现)
- Leetcode Convert a Number to Hexadecimal 405
- [Leetcode] Convert a Number to Hexadecimal
- [LeetCode] Convert a Number to Hexadecimal 数字转为十六进制
- LeetCode Convert a Number to Hexadecimal
- leetcode-456-Convert a Number to Hexadecimal
- LeetCode -- Convert a Number to Hexadecimal
- Leetcode: Convert a Number to Hexadecimal
- 【LeetCode】Convert a Number to Hexadecimal 解题报告
- leetcode[Convert a Number to Hexadecimal]//待整理多种解法
- [LeetCode]Convert a Number to Hexadecimal(Java)
- Convert a Number to Hexadecimal
- convert-a-number-to-hexadecimal