File tree Expand file tree Collapse file tree 3 files changed +117
-0
lines changed
excel_sheet_column_number_171 Expand file tree Collapse file tree 3 files changed +117
-0
lines changed Original file line number Diff line number Diff line change 1+ # 171. Excel Sheet Column Number
2+
3+ https://leetcode.com/problems/excel-sheet-column-number/
4+
5+ ## Difficulty:
6+
7+ Easy
8+
9+ ## Description
10+
11+ Given a column title as appear in an Excel sheet, return its corresponding column number.
12+
13+ For example:
14+ ```
15+ A -> 1
16+ B -> 2
17+ C -> 3
18+ ...
19+ Z -> 26
20+ AA -> 27
21+ AB -> 28
22+ ...
23+ ```
24+
25+ Example 1:
26+ ```
27+ Input: "A"
28+ Output: 1
29+ ```
30+ Example 2:
31+ ```
32+ Input: "AB"
33+ Output: 28
34+ ```
35+ Example 3:
36+ ```
37+ Input: "ZY"
38+ Output: 701
39+ ```
40+
41+ Constraints:
42+ - 1 <= s.length <= 7
43+ - s consists only of uppercase English letters.
44+ - s is between "A" and "FXSHRXW".
Original file line number Diff line number Diff line change 1+ package excel_sheet_column_number_171
2+
3+ import "math"
4+
5+ func titleToNumber (s string ) int {
6+ var res int
7+ var exponent float64
8+ for i := len (s ) - 1 ; i > - 1 ; i -- {
9+ charNum := int (s [i ]- 'A' ) + 1
10+ res += charNum * int (math .Pow (float64 (26 ), exponent ))
11+ exponent ++
12+ }
13+ return res
14+ }
Original file line number Diff line number Diff line change 1+ package excel_sheet_column_number_171
2+
3+ import (
4+ "testing"
5+
6+ "github.com/stretchr/testify/assert"
7+ )
8+
9+ func Test_titleToNumber (t * testing.T ) {
10+ type args struct {
11+ s string
12+ }
13+ tests := []struct {
14+ name string
15+ args args
16+ want int
17+ }{
18+ {
19+ name : "excel sheet column number" ,
20+ args : args {
21+ s : "A" ,
22+ },
23+ want : 1 ,
24+ },
25+ {
26+ name : "excel sheet column number" ,
27+ args : args {
28+ s : "AB" ,
29+ },
30+ want : 28 ,
31+ },
32+ {
33+ name : "excel sheet column number" ,
34+ args : args {
35+ s : "ZY" ,
36+ },
37+ want : 701 ,
38+ },
39+ {
40+ name : "excel sheet column number" ,
41+ args : args {
42+ s : "YB" ,
43+ },
44+ want : 652 ,
45+ },
46+ {
47+ name : "excel sheet column number" ,
48+ args : args {
49+ s : "AAA" ,
50+ },
51+ want : 703 ,
52+ },
53+ }
54+ for _ , tt := range tests {
55+ t .Run (tt .name , func (t * testing.T ) {
56+ assert .Equal (t , tt .want , titleToNumber (tt .args .s ))
57+ })
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments