zoukankan      html  css  js  c++  java
  • 3月3日(5) Roman to Integer

    原题 Roman to Integer

    题意很简单,把Roman字母翻译成int。

    实现方式也不难,针对每个字符转成int,从右往左,依次判断,如果当前值比上一个值大则相加,小则相减。

    什么,你问我怎么想到的,看Roman的定义,写着写着就想出来了,注意19的Roman为 XIX,从右往左处理比较方便。

    class Solution {
    public:
        int romanToInt(string s) {
            int ret = 0;
            int last_t = 0;
            
            for (int i = s.length()-1; i>=0; --i)
            {
                int t;
                switch(s[i])
                {
                    case 'I':
                        t = 1;
                        break;
                    case 'V':
                        t = 5;
                        break;
                    case 'X':
                        t = 10;
                        break;
                    case 'L':
                        t = 50;
                        break;
                    case 'C':
                        t = 100;
                        break;
                    case 'D':
                        t = 500;
                        break;
                    case 'M':
                        t = 1000;
                        break;
                    default:
                        t = 0;
                }
                if (last_t <= t)
                {
                    ret += t;
                } 
                else {
                    ret -= t;
                }
                last_t = t;
            }
            return ret;
        }
    };
  • 相关阅读:
    JSP(一)
    设计模式之UML类图
    Servle原理
    Servlet 浅谈(三)
    Servlet 浅谈(二)
    Servlet 浅谈(一)
    闲聊
    设计模式之装饰器模式
    struts2源码调试环境的搭建
    Github学习
  • 原文地址:https://www.cnblogs.com/seenthewind/p/3579013.html
Copyright © 2011-2022 走看看