给定一个数字,找到其对应的罗马数字。
例子:
Input : 9
Output : IX
Input : 40
Output : XL
Input : 1904
Output : MCMIV
以下是罗马符号的列表,其中还包括减号:
SYMBOL VALUE
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50
XC 90
C 100
CD 400
D 500
CM 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
解释:
解释:
步骤1
- 初始编号= 3549
- 由于3549> = 1000;最初的最大基值将是1000。
- 除以3549/1000。商= 3,余数= 549。对应的符号M将重复三次。
第2步
- 现在,数字= 549
- 1000> 549> = 500;最大基值将是500。
- 除以549/500。商= 1,余数= 49。对应的符号D将重复一次。
第三步
- 现在,数字= 49
- 50> 49> = 40;最大基值为40。
- 除以49/40。商= 1,余数=9。相应的符号XL将重复一次。
第四步
- 现在,数字= 9
- 10> 9> = 9;最大基值为9。
- 除以9/9。商= 1,余数=0。相应的符号IX将重复一次。
第5步
- 最终数字变为0,算法在此处停止。
- 获得的输出为MMMDXLIX。
以下是上述算法的实现:
C++
// C++ Program to convert decimal number to
// roman numerals
#include
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<
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
# Function to convert decimal to Roman Numerals
def printRoman(number):
num = [1, 4, 5, 9, 10, 40, 50, 90,
100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL",
"L", "XC", "C", "CD", "D", "CM", "M"]
i = 12
while number:
div = number // num[i]
number %= num[i]
while div:
print(sym[i], end = "")
div -= 1
i -= 1
# Driver code
if __name__ == "__main__":
number = 3549
print("Roman numeral is:", end = " ")
printRoman(number)
# This code is contributed by
# sanjeev2552
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
C++
// C++ Program for above approach
#include
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 hundereds = c[(num%1000)/100];
string tens = x[(num%100)/10];
string ones = i[num%10];
string ans = thousands + hundereds + 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 hundereds = c[(num%1000)/100];
String tens = x[(num%100)/10];
String ones = i[num%10];
String ans = thousands + hundereds + 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]
hundereds = c[(num % 1000) // 100]
tens = x[(num % 100) // 10]
ones = i[num % 10]
ans = (thousands + hundereds +
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 hundereds = c[(num%1000)/100];
String tens = x[(num%100)/10];
String ones = i[num%10];
String ans = thousands + hundereds + tens + ones;
return ans;
}
// Driver program to test above function
public static void Main()
{
int number = 3549;
Console.WriteLine(intToRoman(number));
}
}
PHP
Python
# 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 = int(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 is: MMMDXLIX
参考资料:http://blog.functionalfun.net/2009/01/project-euler-89-converting-to-and-from.html
另一种方法1 :
在这种方法中,我们必须首先观察该问题。问题陈述中给出的数字最多可以为4位数字。解决此问题的想法是:
- 将给定数字在一个,两个,几百或几千个不同的地方分成数字。
- 从千位开始打印相应的罗马值。例如,如果千位的数字为3,则打印罗马等值3000。
- 重复第二步,直到到达一个位置。
范例:
假设输入数字为3549。因此,从千位开始,我们将开始打印罗马等值字。在这种情况下,我们将按照以下顺序打印:
第一:相当于3000的罗马字母
第二名:相当于罗马的500
第三名:相当于罗马的40
第四名:相当于罗马的9
因此,输出为: MMMDXLIX
以下是上述想法的实现。
C++
// C++ Program for above approach
#include
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 hundereds = c[(num%1000)/100];
string tens = x[(num%100)/10];
string ones = i[num%10];
string ans = thousands + hundereds + 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 hundereds = c[(num%1000)/100];
String tens = x[(num%100)/10];
String ones = i[num%10];
String ans = thousands + hundereds + 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]
hundereds = c[(num % 1000) // 100]
tens = x[(num % 100) // 10]
ones = i[num % 10]
ans = (thousands + hundereds +
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 hundereds = c[(num%1000)/100];
String tens = x[(num%100)/10];
String ones = i[num%10];
String ans = thousands + hundereds + tens + ones;
return ans;
}
// Driver program to test above function
public static void Main()
{
int number = 3549;
Console.WriteLine(intToRoman(number));
}
}
的PHP
输出:
MMMDXLIX
感谢Shashwat Jain提供了上述解决方案。
另一种方法2 ::
在这种方法中,我们考虑数字中的主要有效数字。例如:在1234中,主要有效数字是1。在345中,主要有效数字是3。
为了提取主要有效数字,我们需要维持一个除数(让我们称之为div),例如1234(因为1234/1000 = 1)和100等于345(345/100 = 3)。
另外,让我们维护一个名为romanNumeral = {1:’I’,5:’V’,10:’X’,50:’L’,100:’C’,500:’D’,1000:’M ‘}
以下是算法:
如果主要有效数字<= 3
- romanNumeral [div] * mainSignificantDigit
如果主要有效数字== 4
- romanNumeral [div] + romanNumeral [div * 5]
如果5 <=主要有效数字<= 8
- romanNumeral [div * 5] +(romanNumeral [div] *(mainSignificantDigit-5))
如果主要有效数字== 3
- romanNumeral [div] + romanNumeral [div * 10]
范例:
假设输入数字为3649。
Iter 1
- 初始编号= 3649
- 主要有效数字为3。Div= 1000。
- 因此,romanNumeral [1000] * 3
- 给:MMM
Iter 2
- 现在,数字= 649
- 主有效数字为6。Div = 100。
- 因此romanNumeral [100 * 5] +(romanNumeral [div] *(6-5))
- 给出:DC
Iter 3
- 现在,数字= 49
- 主要有效数字为4。Div = 10。
- 所以romanNumeral [10] + romanNumeral [10 * 5]
- 给:XL
Iter 4
- 现在,数字= 9
- 主要有效数字为9。Div = 1。
- 因此romanNumeral [1] * romanNumeral [1 * 10]
- 给出:IX
通过合并以上所有内容而获得最终结果:MMMDCXLIX
以下是上述想法的Python实现。
Python
# 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 = int(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