summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOlivier Mengué <dolmen@cpan.org>2019-02-02 04:05:01 +0100
committerxuri <xuri.me@gmail.com>2019-02-02 11:05:01 +0800
commite780e41e0222517caa9c69030b5955ab2b458a49 (patch)
tree4fd0a659471568e314e13dc12ea9b4fd26968c32
parentb7b925c03fa611b0157214357cc7f7b949b32992 (diff)
Faster TitleToNumber (#343)
* TestTitleToNumber: more test cases * TitleToNumber: drop use of math.Pow() Compute using pure integers * TitleToNumber: simplify Remove unecessary casts to int
-rw-r--r--excelize_test.go4
-rw-r--r--lib.go13
2 files changed, 10 insertions, 7 deletions
diff --git a/excelize_test.go b/excelize_test.go
index 6a106ec..ebbfcf7 100644
--- a/excelize_test.go
+++ b/excelize_test.go
@@ -1546,8 +1546,12 @@ func TestConditionalFormatError(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, 51, TitleToNumber("AZ"))
}
func TestSharedStrings(t *testing.T) {
diff --git a/lib.go b/lib.go
index 99c513e..30a20e0 100644
--- a/lib.go
+++ b/lib.go
@@ -14,7 +14,6 @@ import (
"bytes"
"io"
"log"
- "math"
"strconv"
"strings"
"unicode"
@@ -91,15 +90,15 @@ func ToAlphaString(value int) string {
// excelize.TitleToNumber("ak")
//
func TitleToNumber(s string) int {
- weight := 0.0
+ weight := 1
sum := 0
for i := len(s) - 1; i >= 0; i-- {
- ch := int(s[i])
- if int(s[i]) >= int('a') && int(s[i]) <= int('z') {
- ch = int(s[i]) - 32
+ ch := s[i]
+ if ch >= 'a' && ch <= 'z' {
+ ch -= 32
}
- sum = sum + (ch-int('A')+1)*int(math.Pow(26, weight))
- weight++
+ sum += int(ch-'A'+1) * weight
+ weight *= 26
}
return sum - 1
}