将介于1到3999之间的十进制数转换为罗马数字

给定一个数字,找出对应的罗马数字。 例如:

null
Input : 9Output : IXInput : 40Output : XLInput :  1904Output : MCMIV

以下是罗马符号列表,其中也包括减法格:

SYMBOL       VALUEI             1IV            4V             5IX            9X             10XL            40L             50XC            90C             100CD            400D             500CM            900 M             1000       

这个想法是将给定数字的单位、十位、百位和千位分别转换。如果数字为0,则没有相应的罗马数字符号。数字4和9的转换与其他数字略有不同,因为这些数字紧跟其后 减法记数法 .

十进制数到罗马数字的转换算法 按1000、900、500、400、100、90、50、40、10、9、5、4、1的顺序将给定的数字与基值进行比较。小于或等于给定数字的基值将是初始基值(最大基值)。将数字除以其最大的基值,相应的基符号将被重复商倍,剩余的将成为未来除法和重复的数字。该过程将重复,直到数字变为零。

演示上述算法的示例:

Convert 3549 to its Roman Numerals

输出:

MMMDXLIX

说明:

说明:

第一步

  • 初始数量=3549
  • 因为3549>=1000;最初最大基值为1000。
  • 除以3549/1000。商=3,余数=549。对应的符号 M 将重复三次。
  • 我们将结果值附加到第二个列表中。
  • 现在余数不等于0,所以我们再次调用该函数。

第二步

  • 现在,数字=549
  • 1000 > 549 >= 500 ; 最大基值为500。
  • 除以549/500。商=1,余数=49。对应的符号 D 将重复一次并停止循环。
  • 我们将结果值附加到第二个列表中。
  • 现在余数不等于0,所以我们再次调用该函数。

第三步

  • 现在,数字=49
  • 50 > 49 >= 40 ; 最大基值为40。
  • 除以49/40。商=1,余数=9。对应的符号 特大号 将重复一次并停止循环。
  • 我们将结果值附加到第二个列表中。
  • 现在余数不等于0,所以我们再次调用该函数。

第四步

  • 现在,数字=9
  • 数字9出现在列表ls中,因此我们直接从dictionary dict中获取值,并将余数设置为0&停止循环。
  • 余数=0。对应的符号 将重复一次,现在余数值为0,因此我们不会再次调用该函数。

第五步

  • 最后,我们加入第二个列表值。
  • 获得的输出 MMMDXLIX。

以下是上述算法的实现:

C++

// C++ Program to convert decimal number to
// roman numerals
#include <bits/stdc++.h>
using namespace std;
// Function to convert decimal to Roman Numerals
int printRoman( int number)
{
int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
string sym[] = { "I" , "IV" , "V" , "IX" , "X" , "XL" , "L" , "XC" , "C" , "CD" , "D" , "CM" , "M" };
int i=12;
while (number>0)
{
int div = number/num[i];
number = number%num[i];
while ( div --)
{
cout<<sym[i];
}
i--;
}
}
//Driver program
int main()
{
int number = 3549;
printRoman(number);
return 0;
}


JAVA

// Java Program to convert decimal number to
// roman numerals
class GFG {
// To add corresponding base symbols in the array
// to handle cases that follow subtractive notation.
// Base symbols are added index 'i'.
static int sub_digit( char num1, char num2, int i, char [] c) {
c[i++] = num1;
c[i++] = num2;
return i;
}
// To add symbol 'ch' n times after index i in c[]
static int digit( char ch, int n, int i, char [] c) {
for ( int j = 0 ; j < n; j++) {
c[i++] = ch;
}
return i;
}
// Function to convert decimal to Roman Numerals
static void printRoman( int number) {
char c[] = new char [ 10001 ];
int i = 0 ;
// If number entered is not valid
if (number <= 0 ) {
System.out.printf( "Invalid number" );
return ;
}
// TO convert decimal number to roman numerals
while (number != 0 ) {
// If base value of number is greater than 1000
if (number >= 1000 ) {
// Add 'M' number/1000 times after index i
i = digit( 'M' , number / 1000 , i, c);
number = number % 1000 ;
} // If base value of number is greater than or
// equal to 500
else if (number >= 500 ) {
// To add base symbol to the character array
if (number < 900 ) {
// Add 'D' number/1000 times after index i
i = digit( 'D' , number / 500 , i, c);
number = number % 500 ;
} // To handle subtractive notation in case of number
// having digit as 9 and adding corresponding base
// symbol
else {
// Add C and M after index i/.
i = sub_digit( 'C' , 'M' , i, c);
number = number % 100 ;
}
} // If base value of number is greater than or equal to 100
else if (number >= 100 ) {
// To add base symbol to the character array
if (number < 400 ) {
i = digit( 'C' , number / 100 , i, c);
number = number % 100 ;
} // To handle subtractive notation in case of number
// having digit as 4 and adding corresponding base
// symbol
else {
i = sub_digit( 'C' , 'D' , i, c);
number = number % 100 ;
}
} // If base value of number is greater than or equal to 50
else if (number >= 50 ) {
// To add base symbol to the character array
if (number < 90 ) {
i = digit( 'L' , number / 50 , i, c);
number = number % 50 ;
} // To handle subtractive notation in case of number
// having digit as 9 and adding corresponding base
// symbol
else {
i = sub_digit( 'X' , 'C' , i, c);
number = number % 10 ;
}
} // If base value of number is greater than or equal to 10
else if (number >= 10 ) {
// To add base symbol to the character array
if (number < 40 ) {
i = digit( 'X' , number / 10 , i, c);
number = number % 10 ;
} // To handle subtractive notation in case of
// number having digit as 4 and adding
// corresponding base symbol
else {
i = sub_digit( 'X' , 'L' , i, c);
number = number % 10 ;
}
} // If base value of number is greater than or equal to 5
else if (number >= 5 ) {
if (number < 9 ) {
i = digit( 'V' , number / 5 , i, c);
number = number % 5 ;
} // To handle subtractive notation in case of number
// having digit as 9 and adding corresponding base
// symbol
else {
i = sub_digit( 'I' , 'X' , i, c);
number = 0 ;
}
} // If base value of number is greater than or equal to 1
else if (number >= 1 ) {
if (number < 4 ) {
i = digit( 'I' , number, i, c);
number = 0 ;
} // To handle subtractive notation in case of
// number having digit as 4 and adding corresponding
// base symbol
else {
i = sub_digit( 'I' , 'V' , i, c);
number = 0 ;
}
}
}
// Printing equivalent Roman Numeral
System.out.printf( "Roman numeral is: " );
for ( int j = 0 ; j < i; j++) {
System.out.printf( "%c" , c[j]);
}
}
//Driver program
public static void main(String[] args) {
int number = 3549 ;
printRoman(number);
}
}
// This code is contributed by PrinciRaj1992


Python3

# Python3 program to convert
# decimal number to roman numerals
ls = [ 1000 , 900 , 500 , 400 , 100 , 90 , 50 , 40 , 10 , 9 , 5 , 4 , 1 ]
dict = { 1 : "I" , 4 : "IV" , 5 : "V" , 9 : "IX" , 10 : "X" , 40 : "XL" , 50 : "L" , 90 : "XC" , 100 : "C" , 400 : "CD" , 500 : "D" , 900 : "CM" , 1000 : "M" }
ls2 = []
# Function to convert decimal to Roman Numerals
def func(no,res):
for i in range ( 0 , len (ls)):
if no in ls:
res = dict [no]
rem = 0
break
if ls[i]<no:
quo = no / / ls[i]
rem = no % ls[i]
res = res + dict [ls[i]] * quo
break
ls2.append(res)
if rem = = 0 :
pass
else :
func(rem,"")
# Driver code
if __name__ = = "__main__" :
func( 3549 , "")
print ("".join(ls2))
# This code is contributed by
# VIKAS CHOUDHARY(vikaschoudhary344)


C#

// C# Program to convert decimal number
// to roman numerals
using System;
class GFG
{
// To add corresponding base symbols in the
// array to handle cases which follow subtractive
// notation. Base symbols are added index 'i'.
static int sub_digit( char num1, char num2,
int i, char [] c)
{
c[i++] = num1;
c[i++] = num2;
return i;
}
// To add symbol 'ch' n times after index i in c[]
static int digit( char ch, int n, int i, char [] c)
{
for ( int j = 0; j < n; j++)
{
c[i++] = ch;
}
return i;
}
// Function to convert decimal to Roman Numerals
static void printRoman( int number)
{
char [] c = new char [10001];
int i = 0;
// If number entered is not valid
if (number <= 0)
{
Console.WriteLine( "Invalid number" );
return ;
}
// TO convert decimal number to
// roman numerals
while (number != 0)
{
// If base value of number is
// greater than 1000
if (number >= 1000)
{
// Add 'M' number/1000 times after index i
i = digit( 'M' , number / 1000, i, c);
number = number % 1000;
}
// If base value of number is greater
// than or equal to 500
else if (number >= 500)
{
// To add base symbol to the character array
if (number < 900)
{
// Add 'D' number/1000 times after index i
i = digit( 'D' , number / 500, i, c);
number = number % 500;
}
// To handle subtractive notation in case
// of number having digit as 9 and adding
// corresponding base symbol
else
{
// Add C and M after index i/.
i = sub_digit( 'C' , 'M' , i, c);
number = number % 100;
}
}
// If base value of number is greater
// than or equal to 100
else if (number >= 100)
{
// To add base symbol to the character array
if (number < 400)
{
i = digit( 'C' , number / 100, i, c);
number = number % 100;
}
// To handle subtractive notation in case
// of number having digit as 4 and adding
// corresponding base symbol
else
{
i = sub_digit( 'C' , 'D' , i, c);
number = number % 100;
}
}
// If base value of number is greater
// than or equal to 50
else if (number >= 50)
{
// To add base symbol to the character array
if (number < 90)
{
i = digit( 'L' , number / 50, i, c);
number = number % 50;
}
// To handle subtractive notation in case
// of number having digit as 9 and adding
// corresponding base symbol
else
{
i = sub_digit( 'X' , 'C' , i, c);
number = number % 10;
}
}
// If base value of number is greater
// than or equal to 10
else if (number >= 10)
{
// To add base symbol to the character array
if (number < 40)
{
i = digit( 'X' , number / 10, i, c);
number = number % 10;
}
// To handle subtractive notation in case of
// number having digit as 4 and adding
// corresponding base symbol
else
{
i = sub_digit( 'X' , 'L' , i, c);
number = number % 10;
}
}
// If base value of number is greater
// than or equal to 5
else if (number >= 5)
{
if (number < 9)
{
i = digit( 'V' , number / 5, i, c);
number = number % 5;
}
// To handle subtractive notation in case
// of number having digit as 9 and adding
// corresponding base symbol
else
{
i = sub_digit( 'I' , 'X' , i, c);
number = 0;
}
}
// If base value of number is greater
// than or equal to 1
else if (number >= 1)
{
if (number < 4)
{
i = digit( 'I' , number, i, c);
number = 0;
}
// To handle subtractive notation in
// case of number having digit as 4
// and adding corresponding base symbol
else
{
i = sub_digit( 'I' , 'V' , i, c);
number = 0;
}
}
}
// Printing equivalent Roman Numeral
Console.WriteLine( "Roman numeral is: " );
for ( int j = 0; j < i; j++)
{
Console.Write( "{0}" , c[j]);
}
}
// Driver Code
public static void Main()
{
int number = 3549;
printRoman(number);
}
}
// This code is contributed by Rajput-Ji


Javascript

<script>
// JavaScript Program to convert decimal number to
// roman numerals
// Function to convert decimal to Roman Numerals
function printRoman(number)
{
let num = [1,4,5,9,10,40,50,90,100,400,500,900,1000];
let sym = [ "I" , "IV" , "V" , "IX" , "X" , "XL" , "L" , "XC" , "C" , "CD" , "D" , "CM" , "M" ];
let i=12;
while (number>0)
{
let div = Math.floor(number/num[i]);
number = number%num[i];
while (div--)
{
document.write(sym[i]);
}
i--;
}
}
//Driver program
let number = 3549;
printRoman(number);
//This code is contributed by Manoj
</script>


输出

MMMDXLIX

参考资料: http://blog.functionalfun.net/2009/01/project-euler-89-converting-to-and-from.html

另一种方法1: : 在这种方法中,我们必须首先观察问题。问题陈述中给出的数字最多可以是4位。解决这个问题的想法是:

  1. 将给定的数字在不同的位置分成数字,如1、2、100或1000。
  2. 从千位开始打印相应的罗马值。例如,如果千位的数字是3,那么打印3000的罗马对应数字。
  3. 重复第二步,直到到达目的地。

实例 : 假设输入号码是3549。所以,从千禧开始,我们将开始印刷罗马版。在这种情况下,我们将按以下顺序打印: 第一 :相当于3000的罗马货币 第二 :相当于500的罗马货币 第三 :罗马相当于40 第四 :罗马相当于9 因此,输出将是: MMMDXLIX

下面是上述想法的实现。

C++

// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate roman equivalent
string intToRoman( int num)
{
// storing roman values of digits from 0-9
// when placed at different places
string m[] = { "" , "M" , "MM" , "MMM" };
string c[] = { "" , "C" , "CC" , "CCC" , "CD" ,
"D" , "DC" , "DCC" , "DCCC" , "CM" };
string x[] = { "" , "X" , "XX" , "XXX" , "XL" ,
"L" , "LX" , "LXX" , "LXXX" , "XC" };
string i[] = { "" , "I" , "II" , "III" , "IV" ,
"V" , "VI" , "VII" , "VIII" , "IX" };
// Converting to roman
string thousands = m[num / 1000];
string hundreds = c[(num % 1000) / 100];
string tens = x[(num % 100) / 10];
string ones = i[num % 10];
string ans = thousands + hundreds + tens + ones;
return ans;
}
// Driver program to test above function
int main()
{
int number = 3549;
cout << intToRoman(number);
return 0;
}


JAVA

// Java Program for above approach
class GFG {
// Function to calculate roman equivalent
static String intToRoman( int num)
{
// storing roman values of digits from 0-9
// when placed at different places
String m[] = { "" , "M" , "MM" , "MMM" };
String c[] = { "" , "C" , "CC" , "CCC" , "CD" ,
"D" , "DC" , "DCC" , "DCCC" , "CM" };
String x[] = { "" , "X" , "XX" , "XXX" , "XL" ,
"L" , "LX" , "LXX" , "LXXX" , "XC" };
String i[] = { "" , "I" , "II" , "III" , "IV" ,
"V" , "VI" , "VII" , "VIII" , "IX" };
// Converting to roman
String thousands = m[num / 1000 ];
String hundreds = c[(num % 1000 ) / 100 ];
String tens = x[(num % 100 ) / 10 ];
String ones = i[num % 10 ];
String ans = thousands + hundreds + tens + ones;
return ans;
}
// Driver program to test above function
public static void main(String[] args)
{
int number = 3549 ;
System.out.println(intToRoman(number));
}
}


Python3

# Python3 program for above approach
# Function to calculate roman equivalent
def intToRoman(num):
# Storing roman values of digits from 0-9
# when placed at different places
m = [" ", " M ", " MM ", " MMM"]
c = [" ", " C ", " CC ", " CCC ", " CD ", " D",
"DC" , "DCC" , "DCCC" , "CM " ]
x = [" ", " X ", " XX ", " XXX ", " XL ", " L",
"LX" , "LXX" , "LXXX" , "XC" ]
i = [" ", " I ", " II ", " III ", " IV ", " V",
"VI" , "VII" , "VIII" , "IX" ]
# Converting to roman
thousands = m[num / / 1000 ]
hundreds = c[(num % 1000 ) / / 100 ]
tens = x[(num % 100 ) / / 10 ]
ones = i[num % 10 ]
ans = (thousands + hundreds +
tens + ones)
return ans
# Driver code
if __name__ = = "__main__" :
number = 3549
print (intToRoman(number))
# This code is contributed by rutvik_56


C#

// C# Program for above approach
using System;
class GFG {
// Function to calculate roman equivalent
static String intToRoman( int num)
{
// storing roman values of digits from 0-9
// when placed at different places
String[] m = { "" , "M" , "MM" , "MMM" };
String[] c = { "" , "C" , "CC" , "CCC" , "CD" ,
"D" , "DC" , "DCC" , "DCCC" , "CM" };
String[] x = { "" , "X" , "XX" , "XXX" , "XL" ,
"L" , "LX" , "LXX" , "LXXX" , "XC" };
String[] i = { "" , "I" , "II" , "III" , "IV" ,
"V" , "VI" , "VII" , "VIII" , "IX" };
// Converting to roman
String thousands = m[num / 1000];
String hundreds = c[(num % 1000) / 100];
String tens = x[(num % 100) / 10];
String ones = i[num % 10];
String ans = thousands + hundreds + tens + ones;
return ans;
}
// Driver program to test above function
public static void Main()
{
int number = 3549;
Console.WriteLine(intToRoman(number));
}
}


PHP

<?php
// PHP Program for above approach
// Function to calculate roman equivalent
function intToRoman( $num )
{
// storing roman values of digits from 0-9
// when placed at different places
$m = array ( "" , "M" , "MM" , "MMM" );
$c = array ( "" , "C" , "CC" , "CCC" , "CD" , "D" ,
"DC" , "DCC" , "DCCC" , "CM" );
$x = array ( "" , "X" , "XX" , "XXX" , "XL" , "L" ,
"LX" , "LXX" , "LXXX" , "XC" );
$i = array ( "" , "I" , "II" , "III" , "IV" , "V" ,
"VI" , "VII" , "VIII" , "IX" );
// Converting to roman
$thousands = $m [ $num / 1000];
$hundreds = $c [( $num % 1000) / 100];
$tens = $x [( $num % 100) / 10];
$ones = $i [ $num % 10];
$ans = $thousands . $hundreds . $tens . $ones ;
return $ans ;
}
// Driver Code
$number = 3549;
echo intToRoman( $number );
// This code is contributed by Akanksha Rai


Javascript

<script>
// JavaScript Program for above approach
// Function to calculate roman equivalent
function intToRoman(num)
{
// storing roman values of digits from 0-9
// when placed at different places
let m = [ "" , "M" , "MM" , "MMM" ];
let c = [ "" , "C" , "CC" , "CCC" , "CD" , "D" ,
"DC" , "DCC" , "DCCC" , "CM" ];
let x = [ "" , "X" , "XX" , "XXX" , "XL" , "L" ,
"LX" , "LXX" , "LXXX" , "XC" ];
let i = [ "" , "I" , "II" , "III" , "IV" , "V" ,
"VI" , "VII" , "VIII" , "IX" ];
// Converting to roman
let thousands = m[Math.floor(num/1000)];
let hundreds = c[Math.floor((num%1000)/100)];
let tens = x[Math.floor((num%100)/10)];
let ones = i[num%10];
let ans = thousands + hundreds + tens + ones;
return ans;
}
// Driver program to test above function
let number = 3549;
document.write(intToRoman(number));
//This code is contributed by Mayank Tyagi
</script>


输出

MMMDXLIX

幸亏 沙什瓦特·贾因 用于提供上述解决方案方法。

另一种方法2: : 在这种方法中,我们考虑数字中的主要有效数字。例:在1234中,主要有效数字是1。类似地,在345中是3。 为了提取出主有效位,我们需要保持一个除数(我们称之为div),比如1000代表1234(因为1234/1000=1),100代表345(345/100=3)。 另外,让我们维护一个名为RomanDimetric={1:’I’,5:’V’,10:’X’,50:’L’,100:’C’,500:’D’,1000:’M’}的字典

以下是算法:

如果主有效位<=3

  • 罗马数字[div]*main有效数字

如果主有效位==4

  • 罗马数字[div]+罗马数字[div*5]

如果5<=主有效位<=8

  • 罗马数字[div*5]+(罗马数字[div]*(主要有效数字-5))

如果主有效位==3

  • 罗马数字[div]+罗马数字[div*10]

实例 : 假设输入的数字是3649。

Iter 1

  • 初始数量=3649
  • 主要有效数字为3。Div=1000。
  • 所以,罗马数字[1000]*3
  • 给:嗯

Iter 2

  • 现在,数字=649
  • 主要有效数字是6。Div=100。
  • 所以罗马数字[100*5]+(罗马数字[div]*(6-5))
  • 给:DC

Iter 3

  • 现在,数字=49
  • 主要有效数字为4。Div=10。
  • 所以罗马数字[10]+罗马数字[10*5]
  • 给出:XL

Iter 4

  • 现在,数字=9
  • 主要有效数字是9。Div=1。
  • 所以罗马数字[1]*罗马数字[1*10]
  • 给出:IX

通过使用上述所有工具获得最终结果:MMMDCXLIX

下面是上述想法的Python实现。

Python3

# Python 3 program to convert Decimal
# number to Roman numbers.
import math
def integerToRoman(A):
romansDict =
{
1 : "I" ,
5 : "V" ,
10 : "X" ,
50 : "L" ,
100 : "C" ,
500 : "D" ,
1000 : "M" ,
5000 : "G" ,
10000 : "H"
}
div = 1
while A > = div:
div * = 10
div / / = 10
res = ""
while A:
# main significant digit extracted
# into lastNum
lastNum = (A / / div)
if lastNum < = 3 :
res + = (romansDict[div] * lastNum)
elif lastNum = = 4 :
res + = (romansDict[div] +
romansDict[div * 5 ])
elif 5 < = lastNum < = 8 :
res + = (romansDict[div * 5 ] +
(romansDict[div] * (lastNum - 5 )))
elif lastNum = = 9 :
res + = (romansDict[div] +
romansDict[div * 10 ])
A = math.floor(A % div)
div / / = 10
return res
# Driver code
print ( "Roman Numeral of Integer is:"
+ str (integerToRoman( 3549 )))


输出

Roman Numeral of Integer is:MMMDXLIX

幸亏 斯利哈沙·桑梅塔 用于提供上述解决方案方法。 本文由 拉胡尔·阿格拉瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享