[LeetCode][Java] Roman to Integer

來源:互聯網
上載者:User

標籤:leetcode   java   roman to integer   

題目:

Given a roman numeral, convert it to an integer.

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


題意:

給定一個羅馬數字,將其轉化為整數。

給定的輸入保證在1-3999之間


演算法分析:


 * 羅馬數字規則:

 * 1, 羅馬數字共有7個,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。

 * 羅馬數字中沒有“0”。

 * 2, 重複次數:一個羅馬數字最多重複3次。

 * 3, 右加左減:

 * 在較大的羅馬數位右邊記上較小的羅馬數字,表示大數字加小數字。

 * 在較大的羅馬數位左邊記上較小的羅馬數字,表示大數字減小數字。


AC代碼:

public class Solution{    private  int sss;    public  int romanToInt(String s)    {      Map<Character, Integer> dct=new HashMap<Character, Integer>() ;      dct.put('I', 1);       dct.put('i', 1);       dct.put('V', 5);       dct.put('v', 5);       dct.put('X', 10);       dct.put('x', 10);       dct.put('L', 50);       dct.put('l', 50);       dct.put('C', 100);       dct.put('c', 100);       dct.put('D', 500);       dct.put('d', 500);      dct.put('M', 1000);       dct.put('m', 1000);       int sum = 0, j;      for(int i = 0; i < s.length(); ++i)      {          j = i+1;          if(j < s.length() && dct.get(s.charAt(j)) > dct.get(s.charAt(i)))          {            sum += dct.get(s.charAt(j)) - dct.get(s.charAt(i));            i = j;          }          else            sum += dct.get(s.charAt(i));      }      return sum;    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] 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.