Leetcode Note: Integer to Roman

Source: Internet
Author: User

Leetcode Note: Integer to Roman

I. Description

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

Ii. Question Analysis

Roman numerals summary:

1 ~ 9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX "};

10 ~ 90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC "};

100 ~ 900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM "};

1000 ~ 3000: {"M", "MM", "MMM "}.

For more information about the Roman number system, see: http://baike.baidu.com/view/1246899.htm

This problem is to enter an Arabic number and convert it to a Roman numeric string.

You can use the simplest operation, that is, to take the low to high digits for the operation. Take one digit at a time, divide the number by 10 after obtaining one digit, and represent the digit with a Roman number. Note that if the current digit is not the original number, you need to increase it by 10 times or 100 times.

Iii. Sample Code

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

 

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.