Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Römische Zahlen (Algorithmen)

Schreiben Sie ein Programm, welches Zahlen (von 1 bis 3000) in das römische Zahlensystem
umwandeln kann. Die römischen Zahlzeichen haben die folgenden Bedeutungen:

  • I = 1
  • V = 5
  • X = 10
  • L = 50
  • C = 100
  • D = 500
  • M = 1000

Beachten Sie, dass es unüblich ist, vier Einer, Zehner oder Hunderter hintereinander zu schreiben. Stattdessen wird der nächste Fünfer, Zehner, ... benutzt und links davon eine Einheit subtrahiert. So ist XC = 90 und XCIX = 99 (selten auch IC).

Zusatzaufgabe: Schreiben Sie auch die Umkehrung, also die Umwandlung römischer Zahlen in unser Stellenwertsystem (10er-System).

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

6 Lösung(en)

public class Main {
    static char romZiff[] = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' };
    static int  romWert[]  = {  1,   5,  10,  50,  100, 500, 1000 };
    
    public static void main(String[] args) {
        String rom = "IC";
        int    dec = 99;

        System.out.println( rom + " = " + rom2dec( rom ) );        
        System.out.println( dec + " = " + dec2rom( dec ) );
    }
    
    public static String dec2rom( int dec ) {
        String tmp, rom = "";
        int ziffer;
        
        if ( dec > 3999 ) {
            rom = "Zu gross";
            return rom;
        }

        for ( int index = 0; dec > 0 ; index += 2 ) {
            tmp = "";
            ziffer = dec % 10;
            if ( ziffer == 4 ) {
                tmp += romZiff[index];
                tmp += romZiff[index+1];
            }
            else if ( ziffer == 9 ) {
                tmp += romZiff[index];
                tmp += romZiff[index+2];
            }
            else {
                if ( ziffer >= 5 ) {
                    tmp += romZiff[index+1];
                    ziffer -= 5;
                }
                for ( ; ziffer > 0; ziffer-- )
                    tmp += romZiff[index];
            }
            dec /= 10;
            rom = tmp + rom;
        }
        
        return rom;
    }
    
    public static int rom2dec( String rom ) {
        int dec = 0;
        int lastVal = 0, curVal;

        char[] ziffern = rom.toUpperCase().toCharArray();

        for( int i = ziffern.length-1; i >= 0; i-- ) {
            curVal = 0;
            for( int j = 0; j < romZiff.length; j++ ) {
                if ( ziffern[i] == romZiff[j] ) {
                    curVal = romWert[j];
                    break;
                }
            }
            if ( curVal == 0 )
                return -1;
            if ( curVal >= lastVal )
                dec += curVal;
            else
                dec -= curVal;
            lastVal = curVal;
        }
        
        return dec;
    }
}

                

romZiff = ['I', 'V', 'X', 'L',  'C', 'D', 'M'  ]
romWert = [  1,   5,  10,  50,  100, 500, 1000 ]



def dec2rom(dec):

    rom = ""
    if dec > 3999:
        rom = "Zahl zu gross"
        return rom
    
    index = 0
    while dec > 0:
    
        tmp = ""
        ziffer = dec % 10
        
        if ziffer == 4:
            tmp += romZiff[index]
            tmp += romZiff[index+1]
    
        elif ziffer == 9:
            tmp += romZiff[index]
            tmp += romZiff[index+2]
        
        else: 
            if ziffer >= 5:
                tmp += romZiff[index+1]
                ziffer -= 5
            
            while ziffer > 0:
                tmp += romZiff[index]
                ziffer -= 1
        
        dec = dec // 10
        rom = tmp + rom
        index += 2
    
    return rom

    
def rom2dec(rom):

    dec     = 0
    lastVal = 0
    ziffern = rom.upper()

    for i in range( len(ziffern)-1, -1, -1 ):
        
        curVal = 0        
        for j in range( 0, len(romZiff) ):
            
            if ziffern[i] == romZiff[j]:
                curVal = romWert[j]
                break
    
        if curVal == 0:
            return -1
        
        elif curVal >= lastVal:
            dec += curVal
        
        else:
            dec -= curVal
        
        lastVal = curVal
    
    return dec


rom = "MCMLXVIII"
dec = 1968

print( rom, " => ", rom2dec(rom) )        
print( dec, " => ", dec2rom(dec) )

                

Lösung von: Alex Groeg (Freies Lernen)

public class romischezahlen {

     int[] dezimalZahlen = { 1, 5, 10, 50, 100, 500, 1000 };
     String[] rom = { "I", "V", "X", "L", "C", "D", "M" };

     public static void main(String[] args) {

          String rom = "XCIVI";
          System.out.println(rom2dez(rom));
     }

     public static int rom2dez(String rom) {
          char[] a;
          a = rom.toCharArray();
          int zahl1 = 0;
          int zahl2 = 0;
          int ergebnis = 0;
          int g;
          int i = 0;

          for (g = 0; g < a.length; g++) {

                if (a[g] == 'I') {
                     zahl2 = 1;
                } else if (a[g] == 'V') {
                     zahl2 = 5;
                } else if (a[g] == 'X') {
                     zahl2 = 10;
                } else if (a[g] == 'L') {
                     zahl2 = 50;
                } else if (a[g] == 'C') {
                     zahl2 = 100;
                } else if (a[g] == 'D') {
                     zahl2 = 500;
                } else if (a[g] == 'M') {
                     zahl2 = 1000;
                }

                if (g < a.length - 1) {
                     i = g + 1;

                     if (a[i] == 'I') {
                          zahl1 = 1;
                     } else if (a[i] == 'V') {
                          zahl1 = 5;
                     } else if (a[i] == 'X') {
                          zahl1 = 10;
                     } else if (a[i] == 'L') {
                          zahl1 = 50;
                     } else if (a[i] == 'C') {
                          zahl1 = 100;
                     } else if (a[i] == 'D') {
                          zahl1 = 500;
                     } else if (a[i] == 'M') {
                          zahl1 = 1000;
                     }

                }
                if (zahl2 < zahl1) {
                     ergebnis -= zahl2;
                } else {
                     ergebnis += zahl2;
                }
          }
          return ergebnis;
     }
}    

                

Lösung von: Name nicht veröffentlicht

function romanNumerals(input) {
  let out, i,
      rom = ['M',  'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
      dec = [1000, 900,  500, 400,  100, 90,   50,  40,   10,  9,    5,   4,    1  ];

  if (typeof input == 'number') decToRom();
  else romToDec();
  }
  return out;

  function decToRom() {
    out = '', i = 0;
    while (input > 0) {
      while (input >= dec[i]) {
        out += rom[i];
        input -= dec[i];
      }
      i++;
    }
  }

  function romToDec() {
    out = 0;
    input = input.toUpperCase().split('');
    // doppelzeichen zusammenfassen (von hinten)
    for (i = input.length-2; i >= 0; i--) {
      tmp = input[i] + input[i+1];
      if (rom.includes(tmp)) {
        input[i] = tmp;
        input.splice(i+1, 1);
      }
    }
    for (i = 0; i < input.length; i++)
      out += dec[rom.indexOf(input[i])];
  }
}

// ausgabe
console.log( romanNumerals(444) );
console.log( romanNumerals ('dclxvi') );                     // lissalanda@gmx.at

                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

// NET 6.x | C# 10.x | VS-2022
var dic = new Dictionary<string, int> {
        {"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}
    };

int RomToDec(string s) {
    var res = 0;
    s = s.ToUpper();

    foreach (var d in dic) res += GetSum(ref s, d.Key, d.Value);
    return res;

    static int GetSum(ref string str, string rom, int val) {
        int r = 0;
        while (str.StartsWith(rom) && str.Length > 0) {
            r += val;
            str = str[rom.Length..];
        }
        return r;
    }
}

string DecToRom(int n) {
    var i = 0;
    var res = string.Empty;
    while (n > 0) {
        var t = dic.ElementAt(i).Value;
        while (n >= t) {
            res += dic.ElementAt(i).Key;
            n -= t;
        }
        i++;
    }
    return res;
}

Console.WriteLine(RomToDec("MCMLXXVII"));
Console.WriteLine(DecToRom(1985));
                

Lösung von: Jens Kelm (@JKooP)

// C++ 14 | VS-2022
#include <iostream>
#include <vector>
#include <algorithm>

struct RomNum {
    std::string rom_str{};
    int rom_val{ 0 };
};

std::vector<RomNum>rom_num{ {"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400}, {"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40}, {"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1} };

int get_sum(std::string& str, const RomNum& rn) {
    auto r{ 0 };
    while (str.substr(0, rn.rom_str.length()) == rn.rom_str && str.length() > 0) {
        r += rn.rom_val;
        str = str.substr(rn.rom_str.length());
    }
    return r;
}

int rom_to_dec(const std::string& s) {
    auto res{ 0 };
    auto str{ s };
    std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return std::toupper(c); });

    for (const auto& rn : rom_num)
        res += get_sum(str, rn);
    return res;
}

std::string dec_to_rom(int n) {
    auto i{ 0 };
    std::string res{};
    while (n) {
        auto t{ rom_num[i].rom_val };
        while (n >= t) {
            res += rom_num[i].rom_str;
            n -= t;
        }
        i++;
    }
    return res;
}

int main() {
    std::cout << rom_to_dec("MCMLXXVII") << "\n";
    std::cout << dec_to_rom(1985) << "\n";
}
                

Lösung von: Jens Kelm (@JKooP)

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 1
Schwierigkeit: k.A.
Webcode: sv9k-jktq
Autor: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen