题目
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
解题思路
该题目可以理解为26进制转换为10进制
从左到右遍历字符串,将每个字符转换成对应的进制,累加进总数,每次累加前总数先乘以进制26
代码
TitleToNumber.go
package _171_Excel_Sheet_Column_Number
func toNumber(tmp byte) int {
return int(tmp - byte('A')) + 1
}
func TitleToNumber(s string) int {
var ret int
len1 := len(s)
for i := 0; i < len1; i++ {
tmp := s[i]
tmpNum := toNumber(tmp)
ret = ret * 26 + tmpNum
}
return ret
}
测试
TitleToNumber_test.go
package _171_Excel_Sheet_Column_Number
import "testing"
func TestTitleToNumber(t *testing.T) {
var tests = []struct{
input string
output int
} {
{"AB", 28},
{"A", 1},
}
for _, test := range tests {
ret := TitleToNumber(test.input)
if ret == test.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", test.output, ret)
}
}
}