0ms cpp solution


  • 0
    Z
    #include <array>
    #include <string>
    class Solution {
    public:
        string toHex(int num) {
            if (num == 0) {
                return "0";
            }
            union {
                int n1;
                unsigned int n2;
            } m;
            m.n1 = num;
            unsigned cnum = m.n2;
            std::array<char, 16> arr({'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'});
            std::string ret("");
            while (cnum > 0) {
                ret.insert(0, 1, arr[cnum & 0xf]);
                cnum /= 16;
            }
            return ret;
        }
    };
    

Log in to reply
 

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