【leetcode】12. Integer to Roman and 13. Roman to Integer 整数与罗马数字互转(中等难度)

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

思维:整数转化为罗马数字
在这里输入是数字,所以不用担心输入的问题,但是每个结果里面有好几种可能。

可以分为四类,
100到300一类,400一类,500到800一类,900最后一类。每一位上的情况都是类似的
分完情况,用数组表示罗马数字和数字的对应,依次遍历循环。

代码:

 //可以分为四轮,1000-1000 100-1000 10-100 1-10
    //每轮可以分为四种情况 1-3 4 5-8 9
    public static String intToRoman(int num) {
        String  res = "";
        char roman[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
        int value[] = {1000, 500, 100, 50, 10, 5, 1};
        for (int n = 0; n < 7; n += 2) {
            int x = num / value[n];
            if (x < 4) {
                for (int i = 1; i <= x; ++i) res += roman[n];
            } else if (x == 4) res = res + roman[n] + roman[n - 1];
            else if (x > 4 && x < 9) {
                res += roman[n - 1];
                for (int i = 6; i <= x; ++i) res += roman[n];
            }
            else if (x == 9) res = res + roman[n] + roman[n - 2];
            num %= value[n];
        }
        return res;
    }
    public static void main(String[] args) {
//        System.out.println(intToRoman(3));
//        System.out.println(intToRoman(4));
//        System.out.println(intToRoman(9));
        System.out.println(intToRoman(58));
//        System.out.println(intToRoman(1994));
    }

罗马数字转整数:

地址https://leetcode.com/problems/roman-to-integer/description/
思维:还是分为四种情况:1-10 10-100 100-1000 1000-10000
每种情况基本一致,只是对应的罗马数字不一样,如果按照从左到右遍历字符串,那么计算result会比较麻烦,因为不知道前面的字符串中的‘I’中的含义,可能是1,可能是10,解决是从倒序遍历,遇到‘I’就是1,累加到result上,如果result大于5,则遇到‘I’就是-1,遇到‘V’就是加5,遇到‘X’和遇到‘I’类似,以此类推

代码:

class Solution {
    public int romanToInt(String s) {
          int sum = 0;
        for (int i = s.length()-1;i>=0;i--){
            char cur = s.charAt(i);
            switch (cur){
                case 'I':
                    sum += (sum>=5)? -1:1;
                    break;
                case 'V':
                    sum +=5;
                    break;
                case 'X':
                    sum += (sum>=50)? -10:10;
                    break;
                case 'L':
                    sum += 50;
                    break;
                case 'C':
                    sum += (sum>=500)? -100:100;
                    break;
                case 'D':
                    sum += 500;
                    break;
                case 'M':
                    sum += (sum>=5000)? -1000:1000;
                    break;
            }
        }
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值