feat: super 包新增 NumberToRome 函数,支持将整数转为罗马数字
This commit is contained in:
parent
9068c57299
commit
5ffd8163f0
|
@ -2,8 +2,20 @@ package super
|
|||
|
||||
import "reflect"
|
||||
|
||||
var (
|
||||
romeThousands = []string{"", "M", "MM", "MMM"}
|
||||
romeHundreds = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
|
||||
romeTens = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
|
||||
romeOnes = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
|
||||
)
|
||||
|
||||
// IsNumber 判断是否为数字
|
||||
func IsNumber(v any) bool {
|
||||
kind := reflect.Indirect(reflect.ValueOf(v)).Kind()
|
||||
return kind >= reflect.Int && kind <= reflect.Float64
|
||||
}
|
||||
|
||||
// NumberToRome 将数字转换为罗马数字
|
||||
func NumberToRome(num int) string {
|
||||
return romeThousands[num/1000] + romeHundreds[num%1000/100] + romeTens[num%100/10] + romeOnes[num%10]
|
||||
}
|
||||
|
|
|
@ -0,0 +1,28 @@
|
|||
package super_test
|
||||
|
||||
import (
|
||||
"github.com/kercylan98/minotaur/utils/super"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNumberToRome(t *testing.T) {
|
||||
tests := []struct {
|
||||
input int
|
||||
output string
|
||||
}{
|
||||
{input: 1, output: "I"},
|
||||
{input: 5, output: "V"},
|
||||
{input: 10, output: "X"},
|
||||
{input: 50, output: "L"},
|
||||
{input: 100, output: "C"},
|
||||
{input: 500, output: "D"},
|
||||
{input: 1000, output: "M"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
result := super.NumberToRome(test.input)
|
||||
if result != test.output {
|
||||
t.Errorf("NumberToRome(%d) = %s; want %s", test.input, result, test.output)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue