zoukankan      html  css  js  c++  java
  • LeetCode13 roman to integer

    Given a roman numeral, convert it to an integer.

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

    从低位开始累加,注意一下像IV和 VI  DC和CD的处理

    class Solution {
    public:
        int romanToInt(string s) 
        {
                int sStart = 0;
        int sEnd   = s.size() - 1;
        int pScan   = sEnd;
    
        int total = 0;
    
        if(sEnd < 0)
        {
            return -1;
        }
    
        while(pScan >= sStart)
        {
            if(s[pScan] == 'X' && total < 50)
            {
                total += 10;
                pScan--;
            }
            if(s[pScan] == 'X' && total >= 50)
            {
                total -= 10;
                pScan--;
            }
            else if(s[pScan] == 'V')
            {
                total += 5;
                pScan--;
            }
            else if(s[pScan] == 'I' && total < 5)
            {
                total += 1;
                --pScan;
            }
            else if(s[pScan] == 'I' && total >= 5)
            {
                total -= 1;
                --pScan;
            }
            else if(s[pScan] == 'L')
            {
                total += 50;
                pScan--;
            }
            else if(s[pScan] == 'C' && total < 500)
            {
                total += 100;
                pScan--;
            }
            else if(s[pScan] == 'C' && total >= 500)
            {
                total -= 100;
                pScan--;
            }
            else if(s[pScan] == 'D')
            {
                total += 500;
                pScan--;
            }
            else if(s[pScan] == 'M')
            {
                total += 1000;
                pScan--;
            }
        }
        return total;
            
            
        }
    };

    if else 语句略长。

  • 相关阅读:
    [bzoj1076]奖励关
    [bzoj1085]骑士精神
    [bzoj1082]栅栏
    [bzoj1084]最大子矩阵
    [bzoj1072]排列
    [bzoj1071]组队
    [bzoj1068]压缩
    [bzoj1061]志愿者招募
    [bzoj1059]矩阵游戏
    [bzoj1052]覆盖问题
  • 原文地址:https://www.cnblogs.com/bestwangjie/p/4448555.html
Copyright © 2011-2022 走看看