JavaScript One-Liner


  • 0
    T

    The idea is come from 1-liner in Python

    But in JavaScript this time:

    var toHex = function(num) {
        return [...'76543210'].map(x => '0123456789abcdef'[(num >>> (x * 4)) & 15]).join('').replace(/^0+(?!$)/g, '');
    };
    

    Note:

    • [...'76543210] result ['7', '6', '5', '4', '3', '2', '1', '0']; x in the map callback is string, but x * 4 will convert it to number automatically
    • >>> is unsigned shift which will convert negative number to positive (-1 to 0xffffffff)
    • /^0+(?!$)/ will match leading zeroes but not the last one

Log in to reply
 

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