Skip to content

Commit c4df897

Browse files
committed
Benchmark and optimize problem 12
1 parent d5ce77e commit c4df897

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

12.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,12 @@ func intToRoman(num int) string {
3030
builder := strings.Builder{}
3131

3232
for _, symbol := range symbols {
33-
for num >= symbol.value {
34-
num -= symbol.value
35-
builder.WriteString(symbol.roman)
36-
}
33+
divisible := num / symbol.value
34+
35+
num -= divisible * symbol.value
36+
37+
repeated := strings.Repeat(symbol.roman, divisible)
38+
builder.WriteString(repeated)
3739
}
3840

3941
return builder.String()

12_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,9 @@ func TestIntToRoman3(t *testing.T) {
3030
t.Errorf("Expected %s but got %s", expected, result)
3131
}
3232
}
33+
34+
func BenchmarkIntToRoman(b *testing.B) {
35+
for i := 0; i < b.N; i++ {
36+
intToRoman(b.N)
37+
}
38+
}

0 commit comments

Comments
 (0)