Advertisement
angryatti

Rómaiszámból Decimális

May 10th, 2022
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. namespace RomanNumberToDecimals
  6. {
  7.     internal class Program
  8.     {
  9.  
  10.         static void Main(string[] args)
  11.         {
  12.  
  13.             Console.WriteLine("Irj be egy római számot");
  14.  
  15.             string numb = Console.ReadLine();
  16.  
  17.             string pattern = @"[IVXLCDM]";
  18.             Regex r = new Regex(pattern);
  19.             if (r.IsMatch(numb))
  20.             {
  21.                 Console.WriteLine(RomanToInt(numb));
  22.  
  23.             }
  24.             else
  25.             {
  26.                 Console.WriteLine("Nem római szám");
  27.  
  28.             }
  29.             Console.ReadKey();
  30.         }
  31.  
  32.         // ez a függvény nem saját!
  33.         public static int RomanToInt(string s)
  34.         {
  35.             int sum = 0;
  36.             Dictionary<char, int> romanNumbersDictionary = new()
  37.             {
  38.                 { 'I', 1 },
  39.                 { 'V', 5 },
  40.                 { 'X', 10 },
  41.                 { 'L', 50 },
  42.                 { 'C', 100 },
  43.                 { 'D', 500 },
  44.                 { 'M', 1000 }
  45.             };
  46.             for (int i = 0; i < s.Length; i++)
  47.             {
  48.                 char currentRomanChar = s[i];
  49.                 romanNumbersDictionary.TryGetValue(currentRomanChar, out int num);
  50.                 if (i + 1 < s.Length && romanNumbersDictionary[s[i + 1]] > romanNumbersDictionary[currentRomanChar])
  51.                 {
  52.                     sum -= num;
  53.                 }
  54.                 else
  55.                 {
  56.                     sum += num;
  57.                 }
  58.             }
  59.             return sum;
  60.         }
  61.     }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement