1 条题解

  • 0
    @ 2021-6-15 13:08:36

    C :

    #include <stdio.h>
    #include <string.h>
    int main()
    {
    	int n,value,i,sum;
    	char a[1001],temp;
    	int tab[26]; 
    	scanf("%d",&n);
    	tab['I'] = 1;
        tab['V'] = 5;
        tab['X'] = 10;
        tab['L'] = 50;
        tab['C'] = 100;
        tab['D'] = 500;
        tab['M'] = 1000;
    	while(n--)
    	{
    		scanf("%s",a);
    		sum=0;
    		for(i=0;i<strlen(a);i++)
    		{
    			value=tab[a[i]];
    			temp=a[i+1];
    			if((temp=='\n')||(temp=='\0')||(tab[temp]<=value))
    			{
    				sum+=value;
    			}
    			else
    			{
    				sum-=value;
    			} 
    		}
    		printf("%d\n",sum); 
    	}
    	return 0;
     } 
    

    C++ :

    #include <iostream>
    using namespace std;
    int main()
    {
    	int a[]={1,5,10,50,100,500,1000};
    	string b="IVXLCDM";
    	int n,i,j;
    	string s;
    	cin>>n;
    	while(n--)
    	{
    		cin>>s;
    		int sum=0,left=0;
    		for(i=0;s[i];i++)
    		{
    			for(j=0;j<7;j++)
    			{
    				if(s[i]==b[j])
    				{
    					if(a[j]>left)
    					sum-=left;
    					else
    					sum+=left;
    					left=a[j];
    					if(i==s.length()-1)
    					sum+=left;
    				}
    			}
    			
    		}
    		cout<<sum<<endl;
    	}
    	return 0;
    }
    

    Java :

    import java.util.Scanner;
    
    public class Main{
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		Scanner in = new Scanner(System.in);
    		Scanner in1 = new Scanner(System.in);
    		int n = in.nextInt();
    		for (int i = 0; i < n; i++) {
    			String s = in.next();
    			int[] a = new int[s.length() + 1];
    			for (int j = 0; j < s.length(); j++) {
    				a[j] = lm(s.charAt(j));
    
    			}
    			//System.out.println(a[2]);
    			int sum = 0;
    			for (int x = s.length() - 1; x >= 0; x--) {
    				if (sum > a[x] && a[x] != a[x + 1]) {
    
    					sum = sum - a[x];
    				} else {
    					// System.out.println("111");
    					sum += a[x];
    					// System.out.println(x);
    				}
    				// System.out.println(sum);
    				// System.out.println(a[x]);
    			}
    			// if(sum>a[0])
    			// System.out.println(sum-a[0]);
    			// else
    			System.out.println(sum);
    		}
    
    	}
    
    	static int lm(char c) {
    		switch (c) {
    		case 'I':
    			return 1;
    		case 'V':
    			return 5;
    		case 'X':
    			return 10;
    		case 'C':
    			return 100;
    
    		case 'L':
    			return 50;
    		case 'D':
    			return 500;
    		case 'M':
    			return 1000;
    		default:
    			break;
    		}
    
    		return 1;
    
    	}
    }
    
    
    • 1

    信息

    ID
    860
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者