Integer to Roman

Source: Internet
Author: User
Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

 

Popularize the Rome notation

The Base

I-1

V-5

X-10

L-50

C-100

D-500

M-1000

If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.

So 'iv 'is '4' and 'vi' is '6 '.

For the numbers above X, only the symbol right before it may be subtracted: So 99 is:Xcix(And notIC).

Note that 4 = IV, 9 = IX, 40 = XL, 90 = XC, 400 = Cd, 900 = cm

The method is very simple. Set up the base number and the character representation corresponding to each base number, and then perform the integer and remainder operations in sequence. The algorithm is relatively simple and you can directly view the Code:

1 class solution {2 public: 3 string inttoroman (INT num) {4 int base [] = {1, 4, 5, 9, 10, 40, 50, 90,100,400,500,900,100 0 }; // The base numbers correspond to the characters in romanchar to 5 char * romanchar [] = {"I", "IV", "V", "IX", "X ", "XL", "L", "XC", "C", "cd", "D", "cm", "M"}; 6 string ans; 7 For (INT I = 12; I> = 0; -- I) {// start from the last base 8 int CNT = num/base [I]; // a bit similar to the simulated 10-digit system. the number on the I-bit is 9 num % = base [I]; // 0 ~ The I-1 bit is the remaining number 10 while (CNT --) ans. append (romanchar [I]); // converts to romanchar11} 12 Return ans; 13} 14 };

 

Roman to integer

 

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 

Integer to Roman

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.