• LeetCode记录之13——Roman to Integer


    能力有限,这道题采用的就是暴力方法,也只超过了39%的用户。需要注意的就是罗马数字如果IXC的后一位比前一位大的采取的是减的方式。

      Given a roman numeral, convert it to an integer.

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

      给定一个罗马数字,将其转换为整数。

      输入保证在1到3999之间。


      

     1 class Solution {
     2     public int romanToInt(String s) {
     3         int length=s.length();
     4         int num=0;
     5         for(int i=0;i<length;i++){
     6             switch (s.charAt(i)) {
     7             case 'I':{
     8                 if((i+1!=length)&&s.charAt(i+1)!='I'){
     9                     num-=1;
    10                     break;
    11                 }
    12                 else {
    13                     num+=1;
    14                     break;
    15                 }
    16             }    
    17             case 'X':
    18                 if((i+1!=length)&&((s.charAt(i+1)=='M')||(s.charAt(i+1)=='D')||(s.charAt(i+1)=='C')||(s.charAt(i+1)=='L'))){
    19                     num-=10;
    20                     break;
    21                 }
    22                 else {
    23                     num+=10;
    24                     break;
    25                 }
    26             case 'C':
    27                 if((i+1!=length)&&((s.charAt(i+1)=='M')||(s.charAt(i+1)=='D'))){
    28                     num-=100;
    29                     break;
    30                 }
    31                 else {
    32                     num+=100;
    33                     break;
    34                 }
    35             case 'M':
    36                 num+=1000;
    37                 break;
    38             case 'V':
    39                 num+=5;
    40                 break;
    41             case 'L':
    42                 num+=50;
    43                 break;
    44             case 'D':
    45                 num+=500;
    46                 break;
    47             default:
    48                 break;
    49             }
    50         }
    51         return num;
    52     }
    53 }
  • 相关阅读:
    python-Web-django-路由保护
    python-Web-django-图表统计
    python-linux-集群nginx
    python-Web-数据库-oracle
    python-Web-数据库-mysql
    python-爬虫-scrapy
    Educational Codeforces Round 90 (Rated for Div. 2) A~C
    leetcode周赛192
    Codeforces Round #597 (Div. 2) C dp
    Codeforces Round #645 (Div. 2) A~D
  • 原文地址:https://www.cnblogs.com/vi3nty/p/7469566.html
Copyright © 2020-2023  润新知