Leetcode-integer to Roman

Source: Internet
Author: User

Question:

Given an integer, convert it to a roman numeral.

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

 

Question Analysis:

After reading the questions for a long time, I couldn't understand what Roman numeral was. So I checked it online and found out what it was, indicating that it was speechless.

Simulation questions:

Basic Characters I V X L C D M
Meanings of corresponding Arabic numerals 1 5 10 50 100 500 1000

1. For the same number, the number is equal to the sum of the numbers, for example, III = 3;

2. If a small number is on the left of a large number, the number is equal to the number reduced by a large number, for example, IV = 4; ix = 9;

3. If a small number is on the right of a large number, the number is equal to the value of a large number plus a small number. For example, Vi = 6; xi = 11;

Code:

class Solution{public:    void setDigit(string &res,int n,char a,char b,char c){           if(n<4){                 for(int i=0;i<n;i++){                         res.push_back(a);                }           }                      else if(n==4){                 res.push_back(a);                 res.push_back(b);           }                      else if(n==5){                 res.push_back(b);           }                      else if(n>5 && n<9){                  res.push_back(b);                  for(int i=5;i<n;i++){                        res.push_back(a);                  }          }                    else if(n==9){              res.push_back(a);              res.push_back(c);          }    }        string intToRoman(int num){          int a1=(num/1000)%10,a2=(num/100)%10,a3=(num/10)%10,a4=num%10;          setDigit(res,a1,‘M‘,‘?‘,‘?‘);          setDigit(res,a2,‘C‘,‘D‘,‘M‘);          setDigit(res,a3,‘X‘,‘L‘,‘C‘);          setDigit(res,a4,‘I‘,‘V‘,‘X‘);          return res;    }};

Refer to what someone else wrote...

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