LeetCode:Roman to Integer

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   ar   for   art   

Given a roman numeral, convert it to an integer.

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

 

  羅馬數字有如下符號:

羅馬字元:   I  V  X   L     C     D       M對應數字:  1  5  10  50  100  500 1000    計數規則:
  1. 相同的數字連寫,所表示的數等於這些數字相加得到的數,例如:III = 3
  2. 小的數字在大的數字右邊,所表示的數等於這些數字相加得到的數,例如:VIII = 8
  3. 小的數字,限於(I、X和C)在大的數字左邊,所表示的數等於大數減去小數所得的數,例如:IV = 4
  4. 正常使用時,連續的數字重複不得超過三次
  5. 在一個數的上面畫橫線,表示這個數擴大1000倍(本題只考慮3999以內的數,所以用不到這條規則)

  思路:從前向後遍曆,當前數字比後一個數字大則加入總和,當前數字(I,X,C)比後一個數字小則從總和中減去該數字。

本文參考了:http://blog.csdn.net/wzy_1988/article/details/17057929

 

 

 1 class Solution { 2     public: 3         int romanToInt(string s) { 4             int str[26]; 5             str[‘I‘-‘A‘]=1; 6             str[‘V‘-‘A‘]=5; 7             str[‘X‘-‘A‘]=10; 8             str[‘L‘-‘A‘]=50; 9             str[‘C‘-‘A‘]=100;10             str[‘D‘-‘A‘]=500;11             str[‘M‘-‘A‘]=1000;12             int sum=0,n=s.size();13             s.push_back(s[n-1]);14             for(int i=0;i<n;i++)15             {16                 if(str[s[i]-‘A‘]>=str[s[i+1]-‘A‘])17                     sum+=str[s[i]-‘A‘];18                 else if(s[i]==‘I‘||s[i]==‘X‘||s[i]==‘C‘)19                     sum-=str[s[i]-‘A‘];20             }21             return sum;22         }23 };

 

LeetCode:Roman to Integer

聯繫我們

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