Faster TitleToNumber (#343)

* TestTitleToNumber: more test cases

* TitleToNumber: drop use of math.Pow()

Compute using pure integers

* TitleToNumber: simplify

Remove unecessary casts to int
This commit is contained in:
Olivier Mengué 2019-02-02 04:05:01 +01:00 committed by xuri
parent b7b925c03f
commit e780e41e02
2 changed files with 10 additions and 7 deletions

View File

@ -1546,8 +1546,12 @@ func TestConditionalFormatError(t *testing.T) {
} }
func TestTitleToNumber(t *testing.T) { func TestTitleToNumber(t *testing.T) {
assert.Equal(t, 0, TitleToNumber("A"))
assert.Equal(t, 25, TitleToNumber("Z"))
assert.Equal(t, 26, TitleToNumber("AA"))
assert.Equal(t, 36, TitleToNumber("AK")) assert.Equal(t, 36, TitleToNumber("AK"))
assert.Equal(t, 36, TitleToNumber("ak")) assert.Equal(t, 36, TitleToNumber("ak"))
assert.Equal(t, 51, TitleToNumber("AZ"))
} }
func TestSharedStrings(t *testing.T) { func TestSharedStrings(t *testing.T) {

13
lib.go
View File

@ -14,7 +14,6 @@ import (
"bytes" "bytes"
"io" "io"
"log" "log"
"math"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
@ -91,15 +90,15 @@ func ToAlphaString(value int) string {
// excelize.TitleToNumber("ak") // excelize.TitleToNumber("ak")
// //
func TitleToNumber(s string) int { func TitleToNumber(s string) int {
weight := 0.0 weight := 1
sum := 0 sum := 0
for i := len(s) - 1; i >= 0; i-- { for i := len(s) - 1; i >= 0; i-- {
ch := int(s[i]) ch := s[i]
if int(s[i]) >= int('a') && int(s[i]) <= int('z') { if ch >= 'a' && ch <= 'z' {
ch = int(s[i]) - 32 ch -= 32
} }
sum = sum + (ch-int('A')+1)*int(math.Pow(26, weight)) sum += int(ch-'A'+1) * weight
weight++ weight *= 26
} }
return sum - 1 return sum - 1
} }