func addComma(num int) string {
str := strconv.Itoa(num)
resultStrBuilder := strings.Builder{}
for i, c := range str {
if i != 0 && !(num < 0 && i == 1) && (len(str)-i)%3 == 0 {
resultStrBuilder.WriteRune(',')
}
resultStrBuilder.WriteRune(c)
}
return resultStrBuilder.String()
}
テストとベンチマーク
func TestAddComma(t *testing.T) {
tests := []struct {
num int
expected string
}{
{0, "0"},
{1, "1"},
{12, "12"},
{123, "123"},
{1234, "1,234"},
{12345, "12,345"},
{123456, "123,456"},
{1234567890, "1,234,567,890"},
{1234567891234567890, "1,234,567,891,234,567,890"},
{-1, "-1"},
{-12, "-12"},
{-123, "-123"},
{-1234, "-1,234"},
{-12345, "-12,345"},
{-123456, "-123,456"},
{-1234567890, "-1,234,567,890"},
{-1234567891234567890, "-1,234,567,891,234,567,890"},
}
for _, test := range tests {
result := addComma(test.num)
if result != test.expected {
t.Errorf("addComma(%d) = %s, expected %s", test.num, result, test.expected)
}
}
}
func BenchmarkAddComma1(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = addComma(1234567890)
}
}
func BenchmarkAddComma2(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = addComma(-1234567890)
}
}
ベンチ結果(M2 MacBook AIR、Dockerコンテナ内で実行)
BenchmarkAddComma1-4 12618339 94.57 ns/op 40 B/op 3 allocs/op
BenchmarkAddComma2-4 12581017 95.65 ns/op 40 B/op 3 allocs/op