ninehills / blog

https://ninehills.tech
758 stars 68 forks source link

LeetCode-12. Integer to Roman #19

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

问题

https://leetcode.com/problems/integer-to-roman/#/description

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

https://en.wikipedia.org/wiki/Roman_numerals

Symbol I V X L C D M
-- 1 5 10 50 100 500 1,000

思路

罗马计数法看起来复杂,其实可以和十进制有个一一对应关系

分位-数字 0 1 2 3 4 5 6 7 8 9
个位 "" I II III IV V VI VII VIII IX
十位 "" X XX XXX XL L LX LXX LXXX XC C
百位 "" C CC CCC CD D DC DCC DCCC CM MC
千位 "" M MM MMM

解决

package main

import "fmt"

// ----------------------
func intToRoman(num int) string {
    r1 := []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
    r2 := []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
    r3 := []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
    r4 := []string{"", "M", "MM", "MMM"}
    return fmt.Sprintf("%v%v%v%v", r4[num/1000], r3[num%1000/100], r2[num%100/10], r1[num%10])
}

// ----------------------

func main() {
    fmt.Println(intToRoman(90))
    fmt.Println(intToRoman(131))
    fmt.Println(intToRoman(13))
}
ninehills commented 7 years ago

20170721