integer-to-roman and roman-to-integer罗马数字转换

来源:互联网 发布:淘宝客服面试注意事项 编辑:程序博客网 时间:2024/05/16 09:07

Given an integer, convert it to a roman numeral.

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

给定一个整形数,将其转换为罗马数字,注意数字上限到3999。

public class Solution {    public String intToRoman(int num) {        String str="";        String symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};        int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};        for(int i=0; num!=0; i++) {             while(num>=value[i]) { //总是选择尽量大的罗马数字                str+=symbol[i];                num-=value[i];            }        }        return str;    }}



Given a roman numeral, convert it to an integer.

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

把罗马数字转换为整形数。

import java.util.HashMap;import java.util.Map;public class Solution {    public int romanToInt(String s) {Map<Character, Integer> map = new HashMap<Character, Integer>();        map.put('I', 1);        map.put('V', 5);        map.put('X', 10);        map.put('L', 50);        map.put('C', 100);        map.put('D', 500);        map.put('M', 1000);        int ans = 0, preVal=0;        for(int i=s.length()-1; i>=0; i--) { //从右向左遍历,即罗马数字更小的一边            int curVal = map.get(s.charAt(i));            if(curVal<preVal) {                ans-=curVal;            } else {                ans+=curVal;            }            preVal = curVal;        }        return ans;    }}







阅读全文
1 0
原创粉丝点击