leetcode之12整数转罗马数字,13罗马数字转整数Golang

没什么好说的,直接上代码吧

整数转罗马数字

func intToRoman(num int) string {
	res := ""
	ch := make([][]string, 4)
	for i := 0; i < 4; i++ {
		ch[i] = make([]string, 3)
		switch i {
		case 0:
			ch[i][0] = "I"
			ch[i][1] = "V"
			ch[i][2] = "X"
		case 1:
			ch[i][0] = "X"
			ch[i][1] = "L"
			ch[i][2] = "C"
		case 2:
			ch[i][0] = "C"
			ch[i][1] = "D"
			ch[i][2] = "M"
		case 3:
			ch[i][0] = "M"
		}
	}
	numArray := make([]int, 4)
	index := 0
	for num != 0 {
		numArray[index] = num % 10
		num /= 10
		index++
	}
	for i := 0; i < 4; i++ {
		tmpStr := ""
		switch numArray[i] {
		case 1, 2, 3:
			for j := 0; j < numArray[i]; j++ {
				tmpStr += ch[i][0]
			}
		case 4:
			tmpStr = ch[i][0] + ch[i][1]
		case 5, 6, 7, 8:
			tmpStr = ch[i][1]
			for j := 5; j < numArray[i]; j++ {
				tmpStr += ch[i][0]
			}
		case 9:
			tmpStr = ch[i][0] + ch[i][2]
		}
		res = tmpStr + res
	}
	// fmt.Println(res)
	return res
}

  罗马数字转整数

func romanToInt(s string) int {
	res := 0
	tMap := make(map[byte]int, 7)
	tMap['I'] = 1
	tMap['V'] = 5
	tMap['X'] = 10
	tMap['L'] = 50
	tMap['C'] = 100
	tMap['D'] = 500
	tMap['M'] = 1000
	l := len(s)
	i := 0
	for i != l {
		if i == l-1 {
			res += tMap[s[i]]
			i++
		} else {
			if tMap[s[i]] >= tMap[s[i+1]] {
				res += tMap[s[i]]
				i++
			} else {
				res += (tMap[s[i+1]] - tMap[s[i]])
				i += 2
			}
		}
	}
	return res
}

  

posted @ 2020-08-18 15:12  胖胖咩  阅读(195)  评论(0)    收藏  举报