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) { return ; } int target = num / (ten/10); 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; }
|