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.

    将罗马数字转成阿拉伯数字。需要了解两者对应关系。

    罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。
    1、重复数次:一个罗马数字重复几次,就表示这个数的几倍。

    2、
    2.1 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
    2.2 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。

    利用规则,可以将字符串对应字符转成对应的数字,存放在数组中,然后将数组中数字相加,相加的时候要满足2.2,即当后一个元素大于前一个元素,表示后一个元素减去前一个元素,也就是和减去前一个元素,加上后一个元素。见代码

     tag:Math,String

    class Solution {
        public int romanToInt(String s) {
            int[] a=new int[s.length()];
            for(int i=0;i<s.length();i++){
                char ch=s.charAt(i);
                if(ch=='I') {a[i]=1;continue;}
                if(ch=='V') {a[i]=5;continue;}
                if(ch=='X') {a[i]=10;continue;}
                if(ch=='L') {a[i]=50;continue;}
                if(ch=='C') {a[i]=100;continue;}
                if(ch=='D') {a[i]=500;continue;}
                if(ch=='M') {a[i]=1000;continue;}
            }
            
            int sum=0;
            for(int i=0;i<a.length-1;i++){
                if(a[i]<a[i+1])
                    sum-=a[i];
                else
                    sum+=a[i];
            }
            
            return sum+a[a.length-1];   //这里因为上面的循环没有操作最后一个数,所以加上最后一个数
        }
    }
  • 相关阅读:
    Kubernetes实战模拟三(wordpress健康检查和服务质量QoS)
    Kubernetes实战模拟二(wordpress高可用)
    Kubernetes实战模拟一(wordpress基础版)
    Rook部署测试Ceph和wordpress实战应用
    kettle作业转换的执行
    BUU BURP COURSE 1
    BUU SQL COURSE 1
    BUU CODE REVIEW 1
    查看FGC
    Pod大量为Evicted被驱逐状态
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8066686.html
Copyright © 2011-2022 走看看