3-liner (build a hex digit with every 4 bits)


  • 0

    Use do while loop to avoid special case for num = 0.

        string toHex(int num) 
        {
            string hex, digits = "0123456789abcdef";      
            
            // build a hex digit with every 4 bits
            do { hex = digits[num & 15]+hex; } while (num = (unsigned int)num >> 4);       
            
            return hex;
        }
    

Log in to reply
 

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