[LeetCode OJ] Roman to Integer

來源:互聯網
上載者:User

標籤:style   blog   http   color   strong   2014   

Given a roman numeral, convert it to an integer.

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

 

下面是百度得到的關於羅馬數的解釋:

 

My Code:

 1 class Solution { 2 public: 3     int romanToInt(string s) { 4         map<char,int> conversion; 5         conversion.insert(make_pair(‘I‘,1)); 6         conversion.insert(make_pair(‘V‘,5)); 7         conversion.insert(make_pair(‘X‘,10)); 8         conversion.insert(make_pair(‘L‘,50)); 9         conversion.insert(make_pair(‘C‘,100));10         conversion.insert(make_pair(‘D‘,500));11         conversion.insert(make_pair(‘M‘,1000));12         int ans=0;13         for(unsigned i=0; i<s.size(); i++)14         {15             if(s[i]==‘V‘ || s[i]==‘L‘ || s[i]==‘D‘) //不能把基本數字V 、L 、D 中的任何一個作為小數放在大數的左邊採用相減的方法構成數目16                 ans += conversion[s[i]];17             else   //基本數字Ⅰ、X 、C 中的任何一個,自身連用構成數目,或者放在大數的右邊連用構成數目,都不能超過三個;放在大數的左邊只能用一個18             {19                 if(i<s.size()-1 && conversion[s[i]]<conversion[s[i+1]])20                 {21                     ans += conversion[s[i+1]]-conversion[s[i]];22                     i++;23                 }24                 else25                     ans += conversion[s[i]];26             }27         }28         return ans;29     }30 };

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.