Leetcode -- 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.

Given an integer, convert it to a Roman number.

The input value can be between 1 and 3999.

Is a conversion rule.

1 2 3 4 5 6 7 8 9
I II III IV V VI VII VIII IX
                 
10 20 30 40 50 60 70 80 90
X Xx Xxx XL L Lx LXX Lxxx XC
                 
100 200 300 400 500 600 700 800 900
C CC CCC CD D DC DCC DCCC Cm
The following program uses the example code to write the above table using if else. Of course, this course schedule is also regular. For example, the course starts with 1-3 and repeats. The last character is intercepted from 4-5, and the last character is added from 6 to 8.

public static String intToRoman(int num) {StringBuffer buf = new StringBuffer();int dddd = num / 1000;int ddd = num % 1000 / 100;int dd = num % 1000 % 100 / 10;int d = num % 1000 % 100 % 10;for(int i=0;i<dddd;i++)buf.append("M");if(ddd == 1)buf.append("C");else if(ddd == 2)buf.append("CC");else if(ddd == 3)buf.append("CCC");else if(ddd == 4)buf.append("CD");else if(ddd == 5)buf.append("D");else if(ddd == 6)buf.append("DC");else if(ddd == 7)buf.append("DCC");else if(ddd == 8)buf.append("DCCC");else if(ddd == 9)buf.append("CM");if(dd == 1)buf.append("X");else if(dd == 2)buf.append("XX");else if(dd == 3)buf.append("XXX");else if(dd == 4)buf.append("XL");else if(dd == 5)buf.append("L");else if(dd == 6)buf.append("LX");else if(dd == 7)buf.append("LXX");else if(dd == 8)buf.append("LXXX");else if(dd == 9)buf.append("XC");if(d == 1)buf.append("I");else if(d == 2)buf.append("II");else if(d == 3)buf.append("III");else if(d == 4)buf.append("IV");else if(d == 5)buf.append("V");else if(d == 6)buf.append("VI");else if(d == 7)buf.append("VII");else if(d == 8)buf.append("VIII");else if(d == 9)buf.append("IX");return buf.toString();}

See this http://www.mathsisfun.com/roman-numerals.html for conversion rules for integers and Roman numerals.

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.