Simple golang solution using a recursion


  • 0
    Y
    func toHex(num int) string {
        
        if num < 0 {
            num = math.MaxUint32 + num + 1
        }
        
        hexStr := ""
        remainder := num % 16
        quotient := num / 16
        
        if quotient > 0 {
            hexStr += toHex(quotient)
        }
    
        if remainder < 16 {
            hexStr += getHex(remainder)
            return hexStr
        }
    
        return "0"
    }
    
    func getHex(remainder int) string {
        if remainder < 10 {
            return fmt.Sprintf("%d", remainder)
        } else {
            return string('a' + remainder - 10)
        }
    }
    

Log in to reply
 

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