zoukankan      html  css  js  c++  java
  • Roman to Integer

    Given a roman numeral, convert it to an integer.

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

    AC最快的一次。。每种字母代表一个数字。小的在左边表示右减左,小的在右边表示右加左。如IV表示4, VI表示6.

    I, i: 1

    V, v: 5

    X, x: 10

    L, l: 50

    C, c: 100

    D, d: 500

    M, m: 1000

     1 class Solution {
     2 public:
     3     int romanToInt(string s) {
     4         int times = 1;
     5         int result = 0;
     6         for(int i = 0; i < s.length() - 1; i++){
     7             if(toint(s[i]) == toint(s[i+1])) times++;
     8             else if(toint(s[i+1]) > toint(s[i])){
     9                 result -= toint(s[i]) * times;
    10                 times = 1;
    11             }
    12             else{
    13                 result += toint(s[i]) * times;
    14                 times = 1;
    15             }
    16         }
    17         result += toint(s[s.length()-1]) * times;
    18         return result;
    19     }
    20     int toint(char ch){
    21         switch(ch){
    22             case 'I': case 'i': return 1;
    23             case 'V': case 'v': return 5;
    24             case 'X': case 'x': return 10;
    25             case 'L': case 'l': return 50;
    26             case 'C': case 'c': return 100;
    27             case 'D': case 'd': return 500;
    28             case 'M': case 'm': return 1000;
    29         }
    30     }
    31 };
  • 相关阅读:
    自我介绍
    企业级应用与互联网应用差异
    Java EE 目标
    自我评价
    第二周———搜查令
    软件工程项目____搜查令
    结对项目--黄金点游戏(邓乐&曾亮)
    wordcount程序
    四则运算 来自 http://www.cnblogs.com/ys1101/p/4368103.html
    问题
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4419543.html
Copyright © 2011-2022 走看看