leetcode 405. Convert a Number to Hexadecimal | &0xf和>>4

Description

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"

My solution

很自然的想到>>4bit方式, &0xf相当于对16取余, 用unordered_map把11,12,13,14,15转为abcdef, 但是细节处理仍有待进步, 具体参见下文discuss优秀答案(基本原理一致).

class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";
        string res;
        unordered_map mp;
        mp[10] = 'a';
        mp[11] = 'b';
        mp[12] = 'c';
        mp[13] = 'd';
        mp[14] = 'e';
        mp[15] = 'f';
        int last, cnt = 0;
        while (num && ++cnt <= 8) {
            last = num & 0xf;
            res = last > 9 ? mp[last] + res : to_string(last) + res;
            num >>= 4;
        }
        return res;
    }
};

Discuss

const string HEX = "0123456789abcdef";
class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";
        string result;
        int count = 0;
        while (num && count++ < 8) {
            result = HEX[(num & 0xf)] + result;
            num >>= 4;
        }
        return result;
    }
};

Reference

  • leetcode 405

你可能感兴趣的:(c++)