#13 Roman to Integer

罗马数字转整数算法
本文介绍了一种将罗马数字转换为整数的算法实现。通过解析罗马数字的构成规律,利用字符映射表获取每个字符对应的数值,并通过前后字符大小比较完成最终整数的计算。

题目链接:https://leetcode.com/problems/roman-to-integer/


Given a roman numeral, convert it to an integer.

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



int Digit(char ch) {
    int ret;
	switch(ch) {
		case 'I':
			return 1;
		case 'V':
			return 5;
		case 'X':
			return 10;
		case 'L':
		    return 50;
		case 'C':
		    return 100;
    	case 'D':
    		return 500;
		case 'M':
		    return 1000;
	}
}
int romanToInt(char* s) {
	int ret = 0;
	int i = strlen(s) - 1;
	if(i >= 0)
		ret = Digit(s[i]);
	for(i = strlen(s) - 2; i >= 0; --i) {       //从数组后向前遍历
		if(Digit(s[i]) < Digit(s[i + 1]))
			ret -= Digit(s[i]);
		else
			ret += Digit(s[i]);
	}
	
	return ret;
}


在C语言中,`case label does not reduce to an integer constant` 错误通常意味着在 `switch` 语句里,`case` 标签使用了非整数常量表达式。`switch` 语句要求 `case` 标签必须是整数常量,像整型字面量、枚举常量或者宏定义的整数常量等。 ### 解决方案 #### 1. 确保 `case` 标签为整数常量 要保证 `case` 后面跟着的是整数常量。例如,下面的代码会产生此错误: ```c #include <stdio.h> int main() { int num = 2; switch (num) { case num: // 错误:num 不是整数常量 printf("This is a problem.\n"); break; default: printf("Default case.\n"); } return 0; } ``` 可将其修改为: ```c #include <stdio.h> int main() { int num = 2; switch (num) { case 2: // 正确:2 是整数常量 printf("This is okay.\n"); break; default: printf("Default case.\n"); } return 0; } ``` #### 2. 若处理字符串,不要用 `switch` 语句 `switch` 语句只能处理整数类型,若要处理字符串,可使用 `if-else if` 语句。例如,在罗马数字转数字的题目中,因为罗马数字是字符串,所以不能用 `switch` 语句: ```c #include <stdio.h> #include <string.h> int romanToInt(char * s) { int result = 0; if (strcmp(s, "I") == 0) { result = 1; } else if (strcmp(s, "V") == 0) { result = 5; } else if (strcmp(s, "X") == 0) { result = 10; } return result; } int main() { char roman[] = "V"; int num = romanToInt(roman); printf("The integer value is: %d\n", num); return 0; } ``` #### 3. 使用枚举类型 如果要处理多个有意义的整数值,可使用枚举类型。例如: ```c #include <stdio.h> enum RomanNumbers { I = 1, V = 5, X = 10 }; int main() { int num = V; switch (num) { case I: printf("Value is I (1).\n"); break; case V: printf("Value is V (5).\n"); break; case X: printf("Value is X (10).\n"); break; default: printf("Unknown value.\n"); } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值