【leetcode刷題筆記】Roman to Integer

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   for   

Given a roman numeral, convert it to an integer.

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

 

題解:轉換的方法:從左往右掃描羅馬字元,如果當前的字元對應的數字比上一個數字小,就直接加上這個數字;否則加上這個數字並且減去上一個數位兩倍,然後更新上一個數字。利用一個HashMap存放羅馬字元和數位對應。

羅馬數字和阿拉伯數位對應表格參見http://www.cnblogs.com/sunshineatnoon/p/3856057.html

例如羅馬數字DCXIX:500+100+10+1+10-2 = 619

代碼如下:

 1 public class Solution { 2     public int romanToInt(String s) { 3         if(s == null || s.length() == 0) 4             return 0; 5          6         HashMap<Character, Integer> map= new HashMap<Character,Integer>(); 7         map.put(‘I‘, 1); 8         map.put(‘V‘, 5); 9         map.put(‘X‘, 10);10         map.put(‘L‘, 50);11         map.put(‘C‘, 100);12         map.put(‘D‘, 500);13         map.put(‘M‘, 1000);14         15         int length = s.length();16         int result = map.get(s.charAt(0));17         int last = result;18         19         for(int i = 1;i < length;i++){20             int temp = map.get(s.charAt(i));21             if(temp <= last)22                 result += temp;23             else24                 result = result + temp - 2*last;25             last = temp;26         }27         28         return result;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.