题目:
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 leading0
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"
解释:
十进制转十六进制。下面这个代码是很简单的形式,其他的解法太长我都不想看了。因为数字是32bit,一个16进制的字符占4位,所以遍历的长度是8。对0进行特殊判断,如果删掉的话,由于lstrip()
函数,最终返回的是""
而不是"0"
python代码:
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num==0:
return '0'
result=''
_hex='0123456789abcdef'
for i in xrange(8):
temp=_hex[num&15]
result=temp+result
num=num>>4
return result.lstrip('0')
class Solution {
public:
string toHex(int num) {
if(num==0)
return "0";
string _hex="0123456789abcdef";
string result="";
for (int i=0;i<8;i++)
{
//取最后4位
auto tmp(_hex[num&15]);
result=tmp+result;
//向右移动4位表示除以16,取下一组
num>>=4;
}
int i=0;
for (auto letter:result)
{
if(letter=='0')
i+=1;
else
break;
}
return result.substr(i,result.size()-i);
}
};
事实上,二进制转十六进制的时候,不需要管是什么类型的,只要从后向前数四位一转,四位一转就好啦,也就是说,一样的十六进制数,在不同的类型下可能表示的是不同的数字比如0xffffffff
在无符号数的时候表示2**32-1
,但是在有符号数的时候表示-1
,题目告诉了是32bit的数字,所以只需要取后32位数转换成unsigned int
类型后,就可以用 while(n)
作为判断条件了(实际上和对8做循环的本质是一样的)。
c++代码:
class Solution {
public:
string toHex(int num) {
string result="";
uint32_t n=num&0xffffffff;
string _hex="0123456789abcdef";
while(n)
{
result=_hex[n&15]+result;
n>>=4;
}
return result.size()?result:"0";
}
};
总结:
Python lstrip()
方法用于截掉字符串左边的空格或指定字符。
c++如何去除字符串中的前导0呢?
答:遍历计数然后取子字符串。
linux系统中用uint32_t类型变量代替unsigned int类型变量。