LeetCode #13 Roman to Integer #Java

來源:互聯網
上載者:User

標籤:java   leetcode   hashmap   

問題
Given a roman numeral, convert it to an integer.

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

Tags: Math, String

代碼

public class Solution {    public int romanToInt(String s) {        Map<Character, Integer> map = new HashMap<Character, Integer>();        map.put(‘I‘, 1);        map.put(‘V‘, 5);        map.put(‘X‘, 10);        map.put(‘L‘, 50);        map.put(‘C‘, 100);        map.put(‘D‘, 500);        map.put(‘M‘, 1000);        int result = 0;        int len = s.length();        for (int i = 0; i < len - 1; i++) {            char c = s.charAt(i);            int add = map.get(c);            switch (c) {//參考文章下面說明中的計算規則                case ‘I‘:                    if (s.charAt(i + 1) == ‘V‘ || s.charAt(i + 1) == ‘X‘) result -= add;                    else result += add;                    break;                case ‘X‘:                    if (s.charAt(i + 1) == ‘L‘ || s.charAt(i + 1) == ‘C‘) result -= add;                    else result += add;                    break;                case ‘C‘:                    if (s.charAt(i + 1) == ‘D‘ || s.charAt(i + 1) == ‘M‘) result -= add;                    else result += add;                    break;                case ‘V‘:                case ‘L‘:                case ‘D‘:                case ‘M‘:                    result += add;                    break;                default:                    break;            }        }        return result + map.get(s.charAt(len - 1));    }}

已耗用時間

說明
羅馬數位計算規則,參考如下幾點:

基底字元
(‘I’, 1) (‘V’, 5) (‘X’, 10) (‘L’, 50) (‘C’, 100) (‘D’, 500) (‘M’, 1000)

1、相同的數字連寫,所表示的數等於這些數字相加得到的數,如:Ⅲ = 3;
2、小的數字在大的數位右邊,所表示的數等於這些數字相加得到的數, 如:Ⅷ = 8;Ⅻ = 12;
3、小的數字,(限於Ⅰ、X 和C)在大的數位左邊,所表示的數等於大數減小數得到的數,如:Ⅳ= 4;Ⅸ= 9;
4、V 和X 左邊的小數字只能用Ⅰ。
5、L 和C 左邊的小數字只能用X。
6、D 和M 左邊的小數字只能用C。

連結:羅馬數字 百度百科

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

LeetCode #13 Roman to Integer #Java

聯繫我們

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