问题描述:给定罗马数字(字符表示)转整数
结题思路:
字符串遍历,转为对应整数,由于一一对应,使用haspmap 建立hasp 表
![](https://i-blog.csdnimg.cn/blog_migrate/5bb1bdc46a1277aae1e739c0b4dd2236.png)
对于4,9这类特殊数字,做特殊处理,根据下图规则可以看出,
表示4,9时,前一个罗马字符小于后一个,据其处理即可,
![](https://i-blog.csdnimg.cn/blog_migrate/a3ce31fd38437166a429b48f4cf36803.png)
答案C语言版本:
#include "errno.h"
#include "string.h"
#define ARRAY_SIZE(x) sizeof(x) / sizeof(x[0])
struct hash_map {
char key;
uint32_t value;
};
static struct hash_map roman_to_inter_convetor[] = {
{
.key = 'I',
.value = 1,
},
{
.key = 'V',
.value = 5,
},
{
.key = 'X',
.value = 10,
},
{
.key = 'L',
.value = 50,
},
{
.key = 'C',
.value = 100,
},
{
.key = 'D',
.value = 500,
},
{
.key = 'M',
.value =1000,
},
};
static struct hash_map* get_hash_map_by_key(char key) {
uint32_t i = 0;
for (i = 0; i < ARRAY_SIZE(roman_to_inter_convetor); i++)
if (roman_to_inter_convetor[i].key == key)
return &roman_to_inter_convetor[i];
return NULL;
}
int romanToInt(char * s) {
uint32_t i = 0;
struct hash_map *mapped = NULL;
uint32_t mapped_value[15] = {0};
uint32_t result = 0;
for (i = 0; i < strlen(s); i++) {
mapped = get_hash_map_by_key(s[i]);
if (!mapped)
return -EINVAL;
mapped_value[i] = mapped->value;
}
for (i = 0; i < strlen(s) -1; i++) {
if (mapped_value[i] < mapped_value[i + 1])
result -= mapped_value[i];
else
result += mapped_value[i];
}
result += mapped_value[i];
return result;
}