using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*Write Date:20230425
rome name :https://b2b.partcommunity.com/community/knowledge/zh_CN/detail/10753/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97#knowledge_article
*/
public class RomeNumberConvert
{
#region 罗马数字转为阿拉伯数字
/// <summary>
/// 罗马数字转为阿拉伯数字
/// </summary>
/// <param name="s">"CII"</param>
/// <returns></returns>
public static int RomeNumberToArabic(string s)
{
s = s.Replace("IV", "a");
s = s.Replace("IX", "b");
s = s.Replace("XL", "c");
s = s.Replace("XC", "d");
s = s.Replace("CD", "e");
s = s.Replace("CM", "f");
int result = 0;
for (int i = 0; i < s.Length; i++)
{
result += WhichArabic(s[i]);
}
return result;
}
private static int WhichArabic(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;
case 'a': return 4;
case 'b': return 9;
case 'c': return 40;
case 'd': return 90;
case 'e': return 400;
case 'f': return 900;
}
return 0;
}
#endregion
#region 阿拉伯数字转为罗马数字
static int[] luomaSign = new int[13] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
/// <summary>
/// 阿拉伯数字转为罗马数字
/// </summary>
/// <param name="val">[1,4000)</param>
/// <returns></returns>
public static string ArabicNumberToRome(int val)
{
string luoma = "";
//int signIndex = 0;
while (val > 0)
{
//换成这样查找可能省点0.0
int signNum = GetSign(val);
if (val >= signNum)
{
val -= signNum;
luoma += WhichRome(signNum);
}
//if (signIndex < luomaSign.Length)
//{
// int signNum = luomaSign[signIndex];
// if (val >= signNum)
// {
// val -= signNum;
// luoma += WhichRome(signNum);
// }
// if (val < signNum)
// {
// signIndex += 1;
// }
//}
}
return luoma;
}
private static string WhichRome(int val)
{
switch (val)
{
case 1: return "I";
case 5: return "V";
case 10: return "X";
case 50: return "L";
case 100: return "C";
case 500: return "D";
case 1000: return "M";
case 4: return "IV";
case 9: return "IX";
case 40: return "XL";
case 90: return "XC";
case 400: return "CD";
case 900: return "CM";
}
return "";
}
private static int GetSign(int target)
{
int signIndex = FindFitSign(luomaSign, target);
signIndex = Mathf.Clamp(signIndex, 0, luomaSign.Length - 1);
return luomaSign[signIndex];
}
static int FindFitSign(int[] nums, int target)
{
if (nums == null || nums.Length == 0)
return -1;
int left = 0, right = nums.Length - 1;
while (left + 1 < right)
{
// Prevent (left + right) overflow
int mid = left + (right - left) / 2;
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] > target)
{
left = mid;
}
else
{
right = mid;
}
}
if (target >= nums[left])
{
return left;
}
if (target >= nums[right])
{
return right;
}
return -1;
}
#endregion
}
罗马数字转换阿拉伯数字计算方式借鉴了LeetCode 罗马数字转整数各位大佬的回答罗马数字转整数l
罗马数字规则见:罗马数字