leetcode 整数转成罗马数字 C#

本文介绍了一种将整数转换为罗马数字的算法实现,通过解析不同位数的数值并映射到相应的罗马数字字符,实现了从1到3999范围内的整数到罗马数字的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正好对应吧,感觉这个可能容易一点

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 整数转罗马数字
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = Convert.ToInt32(Console.ReadLine());
            string str = intToRoman(num);
            Console.WriteLine(str);
            Console.ReadKey();
        }
        public static string intToRoman(int num)
        {
            string Outnum = "";
            int n;
            int index = 0;
            while (num > 0)
            {
                n = num % 10;
                num = (num - n)/10;
                index++;
                Outnum = ChangeString(n, index) + Outnum;
            }
            return Outnum;
        }

        private static string ChangeString(int n, int index)
        {
            string str = "";
            string str1;
            string str2;
            string str3;
            if (index == 1)
            {
                str1 = "I";
                str2 = "V";
                str3 = "X";
            }
            else if (index == 2)
            {
                str1 = "X";
                str2 = "L";
                str3 = "C";
            }
            else if (index == 3)
            {
                str1 = "C";
                str2 = "D";
                str3 = "M";
            }
            else
            {
                str1 = "M";
                str2 = "";
                str3 = "";

            }
            switch (n)
            {
                case 0:

                    break;
                case 1:
                    str += str1;
                    break;
                case 2:
                    str += str1 + str1;
                    break;
                case 3:
                    str += str1 + str1 + str1;
                    break;
                case 4:
                    str += str1 + str2;
                    break;
                case 5:
                    str += str2;
                    break;
                case 6:
                    str += str2 + str1;
                    break;
                case 7:
                    str += str2 + str1 + str1;
                    break;
                case 8:
                    str += str2 + str1 + str1 + str1;
                    break;
                case 9:
                    str += str1 + str3;
                    break;
            }
            return str;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值