LeetCode-Convert_a_Number_to_Hexadecimal

本文介绍了一种不依赖库函数的整数到十六进制字符串的转换算法,适用于32位有符号整数范围内的数值,包括负数的二补码表示。通过位运算实现了高效转换。

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

题目:

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. 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.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. 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.十六进制中的所有字母都小写。

2.十六进制的字符串中不能包含额外的 0。如果给定数字是0,它被表示为一个单独的0字符 '0'

3.给定的数字保证适合在32位有符号整数的范围内。

4.你不得使用库直接将数字转换/格式化为十六进制的任何方法。


例子1:

输入:
26

输出:
"1a"

例子2:

输入:
-1

输出:
"ffffffff"


思路:

给定一个数字num的二进制表示中,每4位代表一个16进制,因此,利用这一特征来进行转换。将num与二进制的15,即‘1111’进行‘与’操作,得到的结果查表Hex="0123456789abcdef",即为num后四位对应的16进制表示,然后将num右移四位,重复上述操作,直到完成num的所有32位。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
	string toHex(int num) {
		string Hex = "0123456789abcdef";
		if (num == 0)
			return "0";
		string result;
		int count = 0;
		while (num && count++ < 8) {   //int类型共32位,故最大循环8次
			result = Hex[(num & 0xf)] + result;   //16进制 0xf:1111
			num >>= 4;
		}
		return result;
	}
};

int main()
{
	Solution s;
	int num = 26;
	string result;
	result = s.toHex(num);
	cout << result;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值