如何在C?
中将整数转换为罗马数字中的字符串表示形式答案 0 :(得分:37)
最简单的方法可能是为复杂案例设置三个数组,并使用一个简单的函数,如:
// convertToRoman:
// In: val: value to convert.
// res: buffer to hold result.
// Out: n/a
// Cav: caller responsible for buffer size.
void convertToRoman (unsigned int val, char *res) {
char *huns[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
char *tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
char *ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
int size[] = { 0, 1, 2, 3, 2, 1, 2, 3, 4, 2};
// Add 'M' until we drop below 1000.
while (val >= 1000) {
*res++ = 'M';
val -= 1000;
}
// Add each of the correct elements, adjusting as we go.
strcpy (res, huns[val/100]); res += size[val/100]; val = val % 100;
strcpy (res, tens[val/10]); res += size[val/10]; val = val % 10;
strcpy (res, ones[val]); res += size[val];
// Finish string off.
*res = '\0';
}
这将处理任何无符号整数,尽管大数字前面会有大量M
个字符,调用者必须确保它们的缓冲区足够大。
一旦数字减少到1000以下,它就是一个简单的3表查找,每个查找数百,数十和单位。例如,假设val
为314
。
val/100
将为3
,因此huns
数组查找将提供CCC
,然后val = val % 100
会为您提供14
tens
查询。
在这种情况下,val/10
将为1
,因此tens
数组查找会提供X
,然后val = val % 10
会为您提供4
ones
查找。
在这种情况下,val
将为4
,因此ones
数组查找将提供IV
。
这为CCCXIV
提供了314
。
缓冲区溢出检查版本是一个简单的步骤:
// convertToRoman:
// In: val: value to convert.
// res: buffer to hold result.
// Out: returns 0 if not enough space, else 1.
// Cav: n/a
int convertToRoman (unsigned int val, char *res, size_t sz) {
char *huns[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
char *tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
char *ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
int size[] = { 0, 1, 2, 3, 2, 1, 2, 3, 4, 2};
// Add 'M' until we drop below 1000.
while (val >= 1000) {
if (sz-- < 1) return 0;
*res++ = 'M';
val -= 1000;
}
// Add each of the correct elements, adjusting as we go.
if (sz < size[val/100]) return 0;
sz -= size[val/100];
strcpy (res, huns[val/100]);
res += size[val/100];
val = val % 100;
if (sz < size[val/10]) return 0;
sz -= size[val/10];
strcpy (res, tens[val/10]);
res += size[val/10];
val = val % 10;
if (sz < size[val) return 0;
sz -= size[val];
strcpy (res, ones[val]);
res += size[val];
// Finish string off.
if (sz < 1) return 0;
*res = '\0';
return 1;
}
尽管如此,你可以考虑将数百,数十和单位的处理重构为一个单独的函数,因为它们非常相似。我会把它作为额外的练习。
答案 1 :(得分:1)
不要在困难的情况下使用娘娘腔的预先计算的地图。
/* roman.c */
#include <stdio.h>
/* LH(1) roman numeral conversion */
int RN_LH1 (char *buf, const size_t maxlen, int n)
{
int S[] = { 0, 2, 4, 2, 4, 2, 4 };
int D[] = { 1000, 500, 100, 50, 10, 5, 1 };
char C[] = { 'M', 'D', 'C', 'L', 'X', 'V', 'I' };
const size_t L = sizeof(D) / sizeof(int) - 1;
size_t k = 0; /* index into output buffer */
int i = 0; /* index into maps */
int r, r2;
while (n > 0) {
if (D[i] <= n) {
r = n / D[i];
n = n - (r * D[i]);
/* lookahead */
r2 = n / D[i+1];
if (i < L && r2 >= S[i+1]) {
/* will violate repeat boundary on next pass */
n = n - (r2 * D[i+1]);
if (k < maxlen) buf[k++] = C[i+1];
if (k < maxlen) buf[k++] = C[i-1];
}
else if (S[i] && r >= S[i]) {
/* violated repeat boundary on this pass */
if (k < maxlen) buf[k++] = C[i];
if (k < maxlen) buf[k++] = C[i-1];
}
else
while (r-- > 0 && k < maxlen)
buf[k++] = C[i];
}
i++;
}
if (k < maxlen) buf[k] = '\0';
return k;
}
/* gcc -Wall -ansi roman.c */
int main (int argc, char **argv)
{
char buf[1024] = {'\0'};
size_t len;
int k;
for (k = 1991; k < 2047; k++)
{
len = RN_LH1(buf, 1023, k);
printf("%3lu % 4d %s\n", len, k, buf);
}
return 0;
}
您实际上不需要声明S
。应该很容易理解为什么。
答案 2 :(得分:0)
我认为ValueConverter是将整数转换为罗马数字的最优雅方法之一。我希望Dante不会因为我在这里发布他的代码而感到愤怒:
public class RomanNumeralizer : IValueConverter
{
private static IList<RomanNumeralPair> _Pairs;
static RomanNumeralizer()
{
var list = new List<RomanNumeralPair>();
list.Add(new RomanNumeralPair(1000, "M"));
list.Add(new RomanNumeralPair(900, "CM"));
list.Add(new RomanNumeralPair(500, "D"));
list.Add(new RomanNumeralPair(400, "CD"));
list.Add(new RomanNumeralPair(100, "C"));
list.Add(new RomanNumeralPair(90, "XC"));
list.Add(new RomanNumeralPair(50, "L"));
list.Add(new RomanNumeralPair(40, "XL"));
list.Add(new RomanNumeralPair(10, "X"));
list.Add(new RomanNumeralPair(9, "IX"));
list.Add(new RomanNumeralPair(5, "V"));
list.Add(new RomanNumeralPair(4, "IV"));
list.Add(new RomanNumeralPair(1, "I"));
_Pairs = list.AsReadOnly();
}
private IList<RomanNumeralPair> PairSet
{
get
{
return _Pairs;
}
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ConvertToRomanNumeral(System.Convert.ToInt32(value));
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
private string ConvertToRomanNumeral(int input)
{
StringBuilder myBuilder = new StringBuilder();
foreach (RomanNumeralPair thisPair in _Pairs)
{
while (input >= thisPair.Value)
{
myBuilder.Append(thisPair.RomanValue);
input -= thisPair.Value;
}
}
return myBuilder.ToString();
}
}
public class RomanNumeralPair
{
private string _RomanValue;
private int _Value;
public RomanNumeralPair(int value, string stringValue)
{
this._Value = value;
this._RomanValue = stringValue;
}
public string RomanValue
{
get
{
return this._RomanValue;
}
}
public int Value
{
get
{
return this._Value;
}
}
}
答案 3 :(得分:0)
#ifndef numberof
#define numberof(A) ((int)(sizeof(A)/sizeof((A)[0])))
#endif
static void roman(char *out, int max, int number)
{
static int romanI[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
static const char *romanA[] = {
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
};
int i, v;
out[0] = 0;
for (i = 0; i < numberof(romanI); i++) {
if (number <= 0)
break;
v = romanI[i];
while (number >= v) {
strcat_s(out, max, romanA[i]);
number -= v;
}
}
}
答案 4 :(得分:-2)
static string ConvertToRoman(int num)
{
int d = 0;
string result = "";
while (num > 0)
{
int n = num % 10;
result = DigitToRoman(n, d) + result;
d++;
num = num / 10;
}
return result;
}
static string DigitToRoman(int n, int d)
{
string[,] map = new string[3, 3] { { "I", "V", "X" }, { "X", "L", "C" }, { "C", "D", "M" } };
string result="";
if (d <= 2)
{
switch (n)
{
case 0:
result = "";
break;
case 1:
result = map[d, 0];
break;
case 2:
result = map[d, 0] + map[d, 0];
break;
case 3:
result = map[d, 0] + map[d, 0] + map[d, 0];
break;
case 4:
result = map[d, 0] + map[d, 1];
break;
case 5:
result = map[d, 1];
break;
case 6:
result = map[d, 1] + map[d, 0];
break;
case 7:
result = map[d, 1] + map[d, 0] + map[d, 0];
break;
case 8:
result = map[d, 1] + map[d, 0] + map[d, 0] + map[d, 0];
break;
case 9:
result = map[d, 0] + map[d, 2];
break;
}
}
else if (d == 3 && n < 5)
{
while (--n >= 0)
{
result += "M";
}
}
else
{
return "Error! Can't convert numbers larger than 4999.";
}
return result;
}