405. Convert a Number to Hexadecimal(python+cpp)

本文介绍了一种将整数转换为十六进制字符串的算法,特别适用于负数的转换,使用了二进制补码方法。通过Python和C++代码实现,展示了去除前导零的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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 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"

解释:
十进制转十六进制。下面这个代码是很简单的形式,其他的解法太长我都不想看了。因为数字是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类型变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值