《leetCode》:Integer to Roman

题目描述

Given an integer, convert it to a roman numeral.

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

思路

由于罗马数字就是由”个“”十“、”百“拼凑而来。因此我们只需要将下面几张表存储起来,然后查表即可

【罗马数字】

1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}. 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
char oneStr[9][5]= {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
char tenStr[9][5]={"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
char hundredStr[9][5]={"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
char thStr[3][5]={"M", "MM", "MMM"};

int my_integerLen(int x){
    int len=0;
    while(x!=0){
        len++;
        x/=10;
    }
    return len;
}
char *strPoint(int len,int temp){
    switch(len){
        case 1:return oneStr[temp-1];
        case 2:return tenStr[temp-1];
        case 3:return hundredStr[temp-1];
        case 4:return thStr[temp-1];
    }
}
char* intToRoman(int num) {
    char *str;
    int len=my_integerLen(num);
    bool flag=true;
    while(num!=0){
        int temp=num/(pow(10,len-1));
        char *str1=strPoint(len,temp);//返回该位代表的字符串 
        if(flag){//第一次进行复制,之后进行连接
            str=(char *)malloc((strlen(str1)+1)*sizeof(char));
            strcpy(str,str1);
            flag=false;
        }
        else{
            strcat(str,str1);//copy到str中。 
        }

        //更新x和其长度 
        num%=((int)(pow(10,len-1)));
        len=my_integerLen(num);
    }
    return str; 
}

int main(void){
    int num;
    while(scanf("%d",&num)!=EOF){
        char *str=intToRoman(num);
        puts(str);
    }
    return 0;
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值