zoukankan      html  css  js  c++  java
  • Leet Code 13.罗马数字转整数

    与12题一样的规则,将罗马数字转为整数。

    思路

    字符串str从左到右遍历,不断将一个长度和两个长度的子字符串与罗马字符匹配,匹配成功就将数值相加

    import java.util.*;
    
    import static java.lang.Math.min;
    
    public class leetcode {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            String str = scan.nextLine();
            int num = romanToInt(str);
            System.out.println(num);
        }
    
        public static int romanToInt(String s) {
            //初始化
            int[] Roman_num = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
            String[] Roman_str = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
    
            int num = 0,index=12;
            boolean equal = false;
            for(int i = 0; i<s.length(); ) {
                equal =false;
                if(s.substring(i,i+1).equals(Roman_str[index])) {
                    num += Roman_num[index];
                    i++;
                    equal = true;
                }
                else if(s.substring(i).length() >= 2 && s.substring(i,i+2).equals(Roman_str[index])) {
                    num += Roman_num[index];
                    i += 2;
                    equal = true;
                }
                if(equal == false) index--;
            }
            return num;
        }
    }
    

    小结

    忘记了String相等不能用==,以至于索引报错,一直在想索引怎么会出错。要注意substring的索引不能超出边界,可以求长度来避免这个情况。

  • 相关阅读:
    [NC13331]城市网络
    Codeforces Round #638 (Div. 2)
    牛客练习赛62
    “科大讯飞杯”第18届上海大学程序设计联赛春季赛暨高校网络友谊赛
    Codeforces Round #635 (Div. 2)
    Codeforces Round #631 (Div. 2)
    牛客每日一题
    Codeforces Round #627 (Div. 3)
    MySQL查看建表语句
    Oracle的number数据类型
  • 原文地址:https://www.cnblogs.com/chenshaowei/p/12613948.html
Copyright © 2011-2022 走看看