zoukankan      html  css  js  c++  java
  • LeetCode(13) - Roman to Integer

      这题和12题是刚好反过来,给你的是一个罗马数字,然后输出一个int。对于这题我并没有用到数组,只根据罗马数字的规则从右往左处理就好,碰到数字比右边最大的要小就减(如IV,右往左读,读到I发现比V要小,故-1),不然就加。代码如下:

     1 public class Solution {
     2     public int romanToInt(String s) {
     3         int lastBigRomaNum = convertChar(s.charAt(s.length() - 1));
     4         int num = lastBigRomaNum;
     5         for (int i = s.length() - 2; i >= 0; i--) {
     6             int roman = convertChar(s.charAt(i));
     7             if (roman < lastBigRomaNum) {
     8                 num -= roman;
     9             } else {
    10                 num += roman;
    11                 lastBigRomaNum = roman;
    12             }
    13         }
    14         return num;
    15     }
    16 
    17     //convert roman char into according integer.
    18     private int convertChar(char c) {
    19         switch (c) {
    20         case 'I': 
    21             return 1;
    22         case 'V':
    23             return 5;
    24         case 'X':
    25             return 10;
    26         case 'L':
    27             return 50;
    28         case 'C':
    29             return 100;
    30         case 'D':
    31             return 500;
    32         case 'M':
    33             return 1000;
    34         default:
    35             return 0;
    36         }
    37     }
    38 }
  • 相关阅读:
    C++的虚函数与多态
    Qt界面的个性设置QSS
    Qt添加背景图片应该注意的问题
    c/c++的函数参数与返回值
    堆和栈
    linux下挂载u盘
    Qt的主窗口弹出消息框
    智能家居实训系统的项目有感!
    Qt 快捷键
    FB
  • 原文地址:https://www.cnblogs.com/kepuCS/p/5244059.html
Copyright © 2011-2022 走看看