Integer to Roman -- leetcode

來源:互聯網
上載者:User

標籤:leetcode   羅馬數字   轉換   

Given an integer, convert it to a roman numeral.

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


class Solution {public:    string intToRoman(int num) {        char symbol[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};        int i = 6;        int weight = 1000;        string result;        while (num) {                const int digit = num / weight;                if (digit <= 3) {                        result.append(digit, symbol[i]);                }                else if (digit == 4) {                        result.append(1, symbol[i]);                        result.append(1, symbol[i+1]);                }                else if (digit == 5) {                        result.append(1, symbol[i+1]);                }                else if (digit <= 8) {                        result.append(1, symbol[i+1]);                        result.append(digit-5, symbol[i]);                }                else {                        result.append(1, symbol[i]);                        result.append(1, symbol[i+2]);                }                num %= weight;                weight /= 10;                i -= 2;        }        return result;    }};

此題的關鍵是對羅馬數字規則的理解。

羅馬數字雖然有七個基底字元,但我覺得對規則的理解可以從I和V兩個字元開始。

I表示1,V表示5.

如何表示阿拉伯數字1-9呢?

1~3, 可以用I來湊數。如I,II, III

4呢,那就5-1, IV (左邊的數字較小則為減)。

5,就是 V

6~8,則用5+, 即先用一個V,不夠的用I來湊數, 如VI, VII, VIII。

9的話,10-1,10就得依靠下一組羅馬數字幫忙了。

 

下一組就是 10,50,

再下一組就是 100, 500,

但組數規則和I V是一樣的,只是符號不一樣,代表的權重不一樣。

 

IV負責個位元

XL負責十位元

CD負責百位元

MV負責千位元

XL負責萬位元

CD負責十萬位元

...


此題目考到3999為止,大概是因為從4000開始,就得用到帶上劃線的字元了。


Integer to Roman -- leetcode

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.