https://leetcode.cn/problems/integer-to-roman/solutions/774611/zheng-shu-zhuan-luo-ma-shu-zi-by-leetcod-75rs/?envType=study-plan-v2&envId=top-interview-150

package leetcode150

import "testing"

/*
    romanMap := map[string]int{
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
        }
*/

func TestIntToRoman(t *testing.T) {
    num := 58
    res := intToRoman(num)
    println(res)
}

func intToRoman(num int) string {
    ans := ""
    pos := 1
    for ; num > 0; num /= 10 {
        d := num % 10
        if pos == 1000 {
            for d > 0 {
                ans = "M" + ans
                d--
            }
        } else if pos == 100 {
            switch d {
            case 4:
                ans = "CD" + ans
            case 9:
                ans = "CM" + ans
            default:
                tStr := ""
                if d >= 5 {
                    tStr += "D"
                    d -= 5
                }
                for d > 0 {
                    tStr += "C"
                    d--
                }
                ans = tStr + ans
            }
        } else if pos == 10 {
            switch d {
            case 4:
                ans = "XL" + ans
            case 9:
                ans = "XC" + ans
            default:
                tStr := ""
                if d >= 5 {
                    tStr += "L"
                    d -= 5
                }
                for d > 0 {
                    tStr += "X"
                    d--
                }
                ans = tStr + ans
            }
        } else if pos == 1 {
            switch d {
            case 4:
                ans = "IV" + ans
            case 9:
                ans = "IX" + ans
            default:
                tStr := ""
                if d >= 5 {
                    tStr += "V"
                    d -= 5
                }
                for d > 0 {
                    tStr += "I"
                    d--
                }
                ans = tStr + ans
            }
        }
        pos *= 10
    }
    return ans
}
// 官方题解
var valueSymbols = []struct {
    value  int
    symbol string
}{
    {1000, "M"},
    {900, "CM"},
    {500, "D"},
    {400, "CD"},
    {100, "C"},
    {90, "XC"},
    {50, "L"},
    {40, "XL"},
    {10, "X"},
    {9, "IX"},
    {5, "V"},
    {4, "IV"},
    {1, "I"},
}

func intToRoman2(num int) string {
    roman := []byte{}
    for _, vs := range valueSymbols {
        for num >= vs.value {
            num -= vs.value
            roman = append(roman, vs.symbol...)
        }
        if num == 0 {
            break
        }
    }
    return string(roman)
}