C# :: Aufgabe #30 :: Lösung #1
8 Lösungen

#30
Zahlen in Römischer Schreibweise
Anfänger - C#
von pocki
- 29.12.2012 um 19:40 Uhr
Schreibe eine Programm welches eine Ganzzahl einliest und diese anschließend in römischer Schreibweise wieder ausgibt und umgekehrt bei einer eingegebenen Zahl in römischer Schreibweise diese als normale Zahl wieder ausgibt:
Die Erkennung der Schreibweise sollte automatisch funktionieren.
Konsolenausgabe:
Geben Sie eine Zahl ein: 1234
entspricht: MCCXXXIV
Geben Sie eine Zahl ein: DXXXVII
entspricht: 537
Die Erkennung der Schreibweise sollte automatisch funktionieren.
#1

von pocki (4190 Punkte)
- 30.12.2012 um 09:51 Uhr
Hier meine Lösung:
C#-Code

void main() { Console.Write("Geben Sie eine Zahl ein: "); string input = Console.ReadLine(); string output = string.Empty; int zahl = 0; if (int.TryParse(input, out zahl)) { output = zahl.IntToRome(); } else { output = input.RomeToInt().ToString(); } Console.WriteLine("entspricht: {0}", output); } public static string IntToRome(this int value) { if ((value < 1) || (value >= Int32.MaxValue)) { return ""; } string res = ""; while (value >= 1000) { value -= 1000; res += "M"; } if (value >= 900) { value -= 900; res += "CM"; } while (value >= 500) { value -= 500; res += "D"; } if (value >= 400) { value -= 400; res += "CD"; } while (value >= 100) { value -= 100; res += "C"; } if (value >= 90) { value -= 90; res += "XC"; } while (value >= 50) { value -= 50; res += "L"; } if (value >= 40) { value -= 40; res += "XL"; } while (value >= 10) { value -= 10; res += "X"; } if (value >= 9) { value -= 9; res += "IX"; } while (value >= 5) { value -= 5; res += "V"; } if (value >= 4) { value -= 4; res += "IV"; } while (value >= 1) { value -= 1; res += "I"; } return res; } public static int RomeToInt(this string value) { if (String.IsNullOrEmpty(value)) { return 0; } int res = 0; while (value.StartsWith("M")) { res += 1000; value = value.Substring(1); } if (value.StartsWith("CM")) { res += 900; value = value.Substring(2); } while (value.StartsWith("D")) { res += 500; value = value.Substring(1); } if (value.StartsWith("CD")) { res += 400; value = value.Substring(2); } while (value.StartsWith("C")) { res += 100; value = value.Substring(1); } if (value.StartsWith("XC")) { res += 90; value = value.Substring(2); } while (value.StartsWith("L")) { res += 50; value = value.Substring(1); } if (value.StartsWith("XL")) { res += 40; value = value.Substring(2); } while (value.StartsWith("X")) { res += 10; value = value.Substring(1); } if (value.StartsWith("IX")) { res += 9; value = value.Substring(2); } while (value.StartsWith("V")) { res += 5; value = value.Substring(1); } if (value.StartsWith("IV")) { res += 4; value = value.Substring(2); } while (value.StartsWith("I")) { res += 1; value = value.Substring(1); } return res; }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1