LintCode: Hex Conversion

Hex Conversion



Similar Problems:


Given a decimal number n and an integer k, Convert decimal number n to base-k.

Example

Example 1:
Given n = 5, k = 2
return "101"
Example 2:
Given n = 30, k = 16
return "1E"

Notice
1.0<=n<=2^31-1, 2<=k<=16
2.Each letter over 9 is indicated in uppercase

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/hex-conversion
// Basic Ideas:
// Complexity: Time O(1), Space O(1)
/**
 * @param n: a decimal number
 * @param k: a Integer represent base-k
 * @return: a base-k number
 */
import (
    "strings"
    "strconv"
    )
func decode(v int) string {
    if v < 10 { return strconv.Itoa(v) }
    return string(byte(v-10+int('A')))
}

func hexConversion (n int, k int) string {
    if n == 0 { return "0" }
    res := []string{}
    negative := false
    if n < 0 {
        n = -n
        negative = true
    }
    for n != 0 {
        res = append([]string{decode(n%k)}, res...)
        n = n/k
    }
    if negative { res = append([]string{"-"}, res...) }
    return strings.Join(res, "")
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.