Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-13. Roman to Integer #20

Closed
ninehills opened this issue Jul 21, 2017 · 1 comment
Closed

LeetCode-13. Roman to Integer #20

ninehills opened this issue Jul 21, 2017 · 1 comment
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Jul 21, 2017

问题

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

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

罗马数字的定义参见: #19

思路

整数转罗马数用的是各位数字查表,罗马数转数字的时候,也有两种办法

  • 识别千百十个位的罗马数,然后查表
  • 只用识别单位的罗马字符,然后根据先后顺序加减

后者显然更简洁

解答

package main

import "fmt"

// ----------------------
func romanToInt(s string) int {
	romanChar := map[byte]int{
		'I': 1,
		'V': 5,
		'X': 10,
		'L': 50,
		'C': 100,
		'D': 500,
		'M': 1000,
	}
	ret := romanChar[s[len(s)-1]]
	for i := len(s) - 2; i >= 0; i-- {
		char := s[i]
		if romanChar[char] < romanChar[s[i+1]] {
			ret = ret - romanChar[char]
		} else {
			ret = ret + romanChar[char]
		}
	}
	return ret
}

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

func main() {
	fmt.Println(romanToInt("MMMCMLXXXIX"))
}
@ninehills
Copy link
Owner Author

20170722

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant