[Leetcode] 整数与罗马数字互换 java

整数→罗马

class Solution {
    public String intToRoman(int num) {
        if(num==0){
            return "";
        }
        int[] number={1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String flag[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        StringBuilder res=new StringBuilder();
        for(int i=0;i<number.length&&num>0;i++){
            if(num<number[i]){
                continue;
            }
            while(num>=number[i]){
                num-=number[i];
                res.append(flag[i]);
            }
        }
        return res.toString();
    }
}

 罗马→数字

class Solution {
    public int romanToInt(String s) {//哈希表
        if(s.length()==0){
            return 0;//return false报错incompatible types: boolean cannot be converted to int
        }
        HashMap<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 l=s.length();
        int result=map.get(s.charAt(l-1));//返回指定索引处的字符。
        for(int i=l-2;i>=0;i--){
            if(map.get(s.charAt(i))>=map.get(s.charAt(i+1))){
                result+=map.get(s.charAt(i));
            }
            else{
                result-=map.get(s.charAt(i));
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/82790003
今日推荐