zoukankan      html  css  js  c++  java
  • 【JAVA、C++】LeetCode 013 Roman to Integer

    Given a roman numeral, convert it to an integer.

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

    解题思路:

    类似上题,方法多多,本题直接给出上题中字典匹配的代码:

    JAVA实现:

    static public int romanToInt(String s) {
        	int num=0;
            String Roman[][] = {
                    {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
                    {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
                    {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
                    {"", "M", "MM", "MMM"}
            };
        	StringBuilder sb=new StringBuilder(s);
        	for(int i=Roman.length-1;i>=0;i--){
        		//由于罗马字母无法表示0,因此,可以认为j>=1
        		for(int j=Roman[i].length-1;j>=1;j--){
        			if(sb.length()>=Roman[i][j].length()&&sb.substring(0,Roman[i][j].length()).equals(Roman[i][j])){
        				num+=j*Math.pow(10, i);
        				sb.delete(0,Roman[i][j].length());
        				break;
        				}
        			}	
        		}	
        	return num;
        }
    

     C++:

     1 class Solution {
     2 public:
     3     int romanToInt(string s) {
     4         int num = 0;
     5         vector<vector<string>> Roman = {
     6             { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" },
     7             { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" },
     8             { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },
     9             { "", "M", "MM", "MMM" }
    10         };
    11         string sb = s;
    12         for (int i = Roman.size() - 1; i >= 0; i--) {
    13             //由于罗马字母无法表示0,因此,可以认为j>=1
    14             for (int j = Roman[i].size() - 1; j >= 1; j--) {
    15                 if (sb.length() >= Roman[i][j].length() && sb.substr(0, Roman[i][j].length())==(Roman[i][j])) {
    16                     num += j*pow(10, i);
    17                     sb.erase(0,Roman[i][j].length());
    18                     break;
    19                 }
    20             }
    21         }
    22         return num;
    23     }
    24 };
  • 相关阅读:
    P4855 MloVtry的idea
    CF343D Water Tree
    CF165D Beard Graph
    P3833 [SHOI2012]魔法树
    P2410 [SDOI2009]最优图像 ZKW最大费用最大流
    P2157 [SDOI2009]学校食堂
    P2407 [SDOI2009]地图复原
    P4008 [NOI2003]文本编辑器
    awk里面执行shell命令
    git 系统中 post-receive 钩子不能正常执行 git pull 解决方法
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4465009.html
Copyright © 2011-2022 走看看