C++ two 5 lines solutions


  • 0

    Use unsigned for num:

    string toHex(int num) {
            string ans = "", itoh = "0123456789abcdef";
    
            for (unsigned number = num, n = number % 16; number; n = (number >>= 4) % 16) {
                ans.push_back(itoh[n]);                                         // convert decimal to hex
            }
            
            return ans.empty() ? "0" : string(ans.rbegin(), ans.rend());        // reverse the result and return it
    }
    

    Use mask on int:

    string toHex(int num) {
            string ans = "", itoh = "0123456789abcdef";
    
            for (int i = 0, n = num & 0xf; num && i < 8; n = (num >>= 4) & 0xf, i++) {
                ans.push_back(itoh[n]);                                         // convert decimal to hex
            }
            
            return ans.empty() ? "0" : string(ans.rbegin(), ans.rend());        // reverse the result and return it
    }
    

Log in to reply
 

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