每日一题00005

罗马数字与数字转换;(11月29日允许发题解)

思路:建立个映射表,将相应字母对应相应数字。每次走到一个字母,顺便判断下一个字母的情况,就ok了。

代码块:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int romanToInt(char* input,int len){
    int romanToIntMap[26] = {
        0,  
        0,  
        100,  
        500, 
        0,  
        0, 
        0,  
        0, 
        1, 
        0, 
        0,  
        50, 
        1000, 
        0,  
        0,  
        0, 
        0, 
        0, 
        0, 
        0,  
        0,  
        5,  
        0,  
        10, 
        0, 
        0   
    };
    int result = 0;
    int i = 0;
    while (i<len) {
        int currentVal = romanToIntMap[input[i] - 'A'];
        int nextVal = romanToIntMap[input[i + 1] - 'A'];
		if(currentVal==0&&nextVal==0)
			return result;
        if (nextVal && currentVal < nextVal&&len>=2) {
            result += (nextVal - currentVal);
            i += 2;
        } else {
            result += currentVal;
            i++;
        }
    }
    return result;
}
void intToRoman(int num) {
    if (num <= 0 || num > 3999){
        return;
    }
    const char *romanNumerals[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
    const int values[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};

    int i = 12; 
    while (num > 0) {
        int quotient = num / values[i];
        num %= values[i];
        for (int j = 0; j < quotient; j++){
            printf("%s", romanNumerals[i]);
        }
        i--;
    }
    printf("\n");
}
int main(){
	char rome[1000]={'0'};
	scanf("%s",rome);
	int si=strlen(rome);
	char s[si];
	for(int i=0;i<si;i++)
	 	s[i]=rome[i];
	const char* romanInput=s;
    int c=atoi(s);
    if(c)
        intToRoman(c);
    else   
   printf("%d\n",romanToInt(rome,si));
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值