LeetCode 罗马字相关

https://leetcode.com/problems/integer-to-roman/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
char ONE[5] = {' ', 'I', 'X', 'C', 'M'};
char FIVE[4] = {' ', 'V', 'L', 'D'};
char strr[100];
int judgeByte(int num, int * byte) {
int ten = 10, tmp = 1;
while (1) {
if (num / ten == 0) {
*byte = tmp;
return ten;
} else {
ten *= 10;
tmp ++;
}
}
}
void produceRomanSymbol(int num, int ten, int byte, char * result) {
if (byte == 0) {
//sprintf(result + strlen(result), "\n");
return ;
}
int target = num / (ten/10);
//printf("num = %d, ten = %d, target = %d, byte = %d\n", num, ten, target, byte);
if (target == 5) {
sprintf(result + strlen(result), "%c", FIVE[byte]);
}
else if (target > 5) {
if (target == 9) {
sprintf(result + strlen(result), "%c%c", ONE[byte], ONE[byte + 1]);
}
else {
int i = 1;
sprintf(result + strlen(result), "%c", FIVE[byte]);
for (; i <= (target - 5); i ++) {
sprintf(result + strlen(result), "%c", ONE[byte]);
}
}
}
else {
if (target == 4) {
sprintf(result + strlen(result), "%c%c", ONE[byte], FIVE[byte]);
}
else {
int i = 1;
for (; i <= target; i ++) {
sprintf(result + strlen(result), "%c", ONE[byte]);
}
}
}
produceRomanSymbol(num % (ten/10), ten / 10, byte - 1, result);
}
char* intToRoman(int num) {
int byte;
int ten = judgeByte(num, &byte);
memset(strr, 0, 100);
produceRomanSymbol(num, ten, byte, strr);
return strr;
}

https://leetcode.com/problems/roman-to-integer/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
int getRomanValue(char ch) {
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;
}
return -1;
}

int romanToInt(char* s) {
int cnt = 0, tmp = 0, i;
for (i = 0; i < strlen(s); i ++) {
// printf("i = %d, ", i);
if (i == 0) {
tmp = getRomanValue(s[i]);
} else {
int diff = getRomanValue(s[i]) - getRomanValue(s[i - 1]);
if (diff == 0) {
tmp += getRomanValue(s[i]);
// printf("** tmp = %d, pos = %c\n", tmp, s[i]);
//cnt += tmp;
} else if(diff > 0) {
cnt += (getRomanValue(s[i]) - tmp);
// printf("cnt = %d, pos = %c\n", cnt, s[i]);
tmp = 0;
} else {
cnt += tmp;
tmp = 0;
tmp += getRomanValue(s[i]);
// printf("tmp = %d, pos = %c\n", tmp, s[i]);
}
}
}
if (tmp != 0)
cnt += tmp;
return cnt;
}
作者

遇寻

发布于

2019-02-27

更新于

2021-02-09

许可协议

评论