C++ like others - but with cheesy branch avoidance


  • 0
    M

    It still runs at '0ms,' so not clear if there's a speed up.

    class Solution {
    public:
        string toHex(int num) 
        {
            unsigned x = num;
    
            if (x == 0)
                return "0";
    
            string result;
    
            const int off[2] = { -10, 0 };
            const int dig[2] = { 'a', '0' };
    
            for(; x; x >>= 4)
            {
                auto nibble = (x & 0xF);
                auto branch = (nibble < 10);
    
                result += dig[branch] + (nibble + off[branch]);
            }
    
            reverse(begin(result), end(result));
            return result;
        }
    };
    

Log in to reply
 

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