LeetCode-Convert_a_Number_to_Hexadecimal

题目:

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;
}

猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80309490
今日推荐