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

    Question: Given a roman numeral, convert it to an integer.

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

    Analysis: 该问题是将输入的罗马数字的字符串转化为整数。 方法:从左到右依次扫描字符串,需要三个变量:temp记录分段数字, lastv表示刚刚扫描过的数字, curv表示当前正在扫描的数字。

    1. 若lastv == curv,则记录变量加上当前字符;

    2. 若lastv < curv,则当前字符减去记录变量记录下的值;

    3.若lastv > curv,记录变量直接加到结果中。

    Answer:

    public class Solution {
            public int romanToInt(String s) {
            if(s == null || s.length() == 0)
                return 0;
            int sum = 0;
            int temp = charToInt(s.charAt(0));
            int lastv = temp;
            for(int i=1; i<s.length(); i++){
                char c = s.charAt(i);
                int curv = charToInt(c);
                
                if(lastv == curv)
                    temp += curv;
                else if(lastv < curv){
                    temp = curv - temp;
                } else {
                    sum += temp;
                    temp = curv;
                }
                lastv = curv;
            }
            sum += temp;
            return sum;
            
        }
        
        private int charToInt(char c) {
            // TODO Auto-generated method stub
            switch(c) {
                case 'I': return 1;
                case 'V': return 5;
                case 'X': return 10;
                case 'L': return 50;
                case 'C': return 100;
                case 'D': return 500;
                case 'M': return 1000;
                default: return 0;
            }
        }
    }
  • 相关阅读:
    Freckles (最小生成树)
    素数筛法 模板
    Least Common Multiple (最小公倍数,先除再乘)
    Watering Grass (贪心,最小覆盖)
    Minimal coverage (贪心,最小覆盖)
    今年暑假不AC (贪心)
    Bzoj1072 [SCOI2007]排列perm
    Bzoj1087 [SCOI2005]互不侵犯King
    POJ1185 炮兵阵地
    POJ3254 Corn Fields
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4776671.html
Copyright © 2011-2022 走看看