Concise C++ Solution


  • 17
    P
    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;
        }
    };
    

  • 0
    O

    Would you mind telling me why you used num & 15 ?


  • 2
    Y

    @OliviaNz It means that he can get half of a byte (range is 0x0 ~ 0xF) in every circulation. An integer number is 4 bytes, so he circulates 8 times.


  • 0
    O

    @Y_Y Thank you so much for your prompt reply. It was very embarrassed to say that I've no idea what you are talking about. I understand an integer number is 4 bytes. What does that got to do with the rest? If it's too troublesome to explain, would you mind giving me some keywords so I can google myself? Thanks again in advance.


  • 3
    Y

    @OliviaNz
    AND operation: http://www.xcprod.com/titan/XCSB-DOC/binary_and.html, the binary of 0xF is 0x1111, so every 4 bits number & 0xF is itself. In other word, An integer number AND with 0xF will get its last 4 bits (0x12345678 & 0x0000000F = 0x00000008).

    Owe to my weak english, I will give you an example to explain it.
    Suppose hex of the num is 0x12345678.
    In first circulation, num &(AND operation) 0xF equals 0x8, then result equals "8". Next execute "num >>= 4", num equals 0x01234567.
    In second circulation, num &(AND operation) 0xF equals 0x7, result equals "78" and so on....


  • 1
    O

    @Y_Y Thank you for your detailed explanation. Sorry, when I said I didn't understand you. That's because I lack of fundamental knowledge. Your English is good. Now I got it. This is a fascinating solution.


  • 0
    G

    class Solution {
    public:
    string toHex(int num) {
    stringstream ss;
    ss<<hex<<num;
    string str;
    ss>>str;
    return str;
    }
    };


  • 0
    S

    Do you even need to check the condition 'count++ < 8' ?
    num would be 0 anyways after doing 'num >>= 4' eight times if you treat it as an unsigned integer


  • 0
    M
    This post is deleted!

  • 0
    T

    HEX[(num & 0xf)] return 0xf for -1 . What is -1 in binary ?. I know MSB will be set but we are ending with only lower 4 bits so it is like 1&0xf ?


  • 0
    W

    @sumit.083 but its type is not unsigned int. Without the condition count++ < 8, it will trap into infinite loop when the input is negative like -1 (0xffff ffff).


  • 0
    E

    actually, we can use unsigned n instead of num.

    unsigned n = num;
    while(n) {
        s = HEX[(num & 0xf)]+ s;
        n >>= 4;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.