Leetcode question | Integer to Roman

Source: Internet
Author: User

Leetcode question | Integer to Roman

Problem:

 

Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.

Converts an integer from 1 to 3999 to a Roman number.

 

 

Thinking:

(1)

Example

Single digit example
I, 1] II, 2] III, 3] IV, 4] V, 5] vi, 6] VII, 7] VIII, 8] IX, 9]
Ten-digit example
X, 10] average, 11] average, 12] XIII, 13] XIV, 14] XV, 15] XVI, 16] XVII, 17] XVIII, 18] XIX, 19] XX, 20] XXI, 21] XXII, 22] XXIX, 29] XXX, 30] XXXIV, 34] XXXV, 35] XXXIX, 39] XL, 40] L, 50] LI, 51] LV, 55] LX, 60] LXV, 65] LXXX, 80] XC, 90] XCIII, 93] XCV, 95] XCVIII, 98] XCIX, 99]
Example of hundreds of BITs
C, 100] CC, 200] CCC, 300] CD, 400] D, 500] DC, 600] DCC, 700] DCCC, 800] CM, 900] CMXCIX, 999]
Example of a thousand bits
M, 1000] MC, 1100] MCD, 1400] MD, 1500] MDC, 1600] MDCLXVI, 1666] MDCCCLXXXVIII, 1888] MDCCCXCIX, 1899] MCM, 1900] MCMLXXVI, 1976] MCMLXXXIV, 1984] MCMXC, 1990] MM, 2000] MMMCMXCIX, 3999]
 

(2) Tips for avoiding N multi-condition judgment: use the law of the Roman numerals to subtract a base to simplify the complexity.

 

Code:

 

class Solution {public:    string intToRoman(int num)    {        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };        string numerals[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };        string result;        for (int i = 0; i < 13; i++) {            while (num >= values[i]) {                num -= values[i];                result.append(numerals[i]);            }        }        return result;    }};


 

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.