Leetcode integer to Roman numeral Java

Source: Internet
Author: User

The Roman numerals contain the following seven characters:,,,, I V X L C , D and M .

Character          value I             1V             5X             10L             50C             100D             500M             1000

For example, the Roman numeral 2 is written II , that is, two parallel 1. 12 Write XII , that is X + II . 27 Write XXVII , that is XX + V + II .

Usually, the number of Roman numerals is small and the numbers are on the right side of the large numbers. But there are exceptions, such as 4 not IIII to write, but IV . The number 1 is on the left side of the number 5, the number represented is equal to the large number 5 decreases the number 1 gets the value 4. Similarly, the number 9 is represented as IX . This special rule applies only to the following six cases:

    • ICan be placed on V X the left side of (5) and (10) to represent 4 and 9.
    • XCan be placed on L C the left side of (50) and (100) to represent 40 and 90.
    • CCan be placed on D M the left side of (500) and (1000) to represent 400 and 900.

Given an integer, convert it to Roman numerals. The input is guaranteed to be within the range of 1 to 3999.

Example 1:

Input: 3 output: "III"

Example 2:

Input: 4 output: "IV"

Example 3:

Input: 9 output: "IX"

Example 4:

Input: 58 Output: "LVIII" Explanation: C = +, L = +, XXX = +, III = 3.

Example 5:

Input: 1994 Output: "MCMXCIV" Explanation: M = +, CM =-, XC = +, IV = 4.
classSolution { PublicString Inttoroman (intnum) {        int[] numarray=New int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1}; String[] Romaarray=Newstring[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuffer SB=NewStringBuffer (); if(num<0| | num>3999)            return NULL;  for(inti=0;i<numarray.length;i++)       {           inttemp=num/Numarray[i];  while(temp>0) {sb.append (romaarray[i]); Temp--; } num=num%Numarray[i]; }          returnsb.tostring (); }}

Submit Results

Leetcode integer to Roman numeral Java

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.