-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path171.excel-sheet-column-number.go
88 lines (83 loc) · 1.28 KB
/
171.excel-sheet-column-number.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import "math"
/*
* @lc app=leetcode id=171 lang=golang
*
* [171] Excel Sheet Column Number
*
* https://leetcode.com/problems/excel-sheet-column-number/description/
*
* algorithms
* Easy (54.11%)
* Likes: 1207
* Dislikes: 165
* Total Accepted: 325.7K
* Total Submissions: 581.9K
* Testcase Example: '"A"'
*
* 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
* ...
*
*
* Example 1:
*
*
* Input: "A"
* Output: 1
*
*
* Example 2:
*
*
* Input: "AB"
* Output: 28
*
*
* Example 3:
*
*
* Input: "ZY"
* Output: 701
*
*
* Constraints:
*
*
* 1 <= s.length <= 7
* s consists only of uppercase English letters.
* s is between "A" and "FXSHRXW".
*
*
*/
// @lc code=start
func titleToNumber(s string) int {
return titleToNumber2(s)
}
func titleToNumber2(s string) int {
retVal, pos := 0, len(s)-1
for _, c := range s {
v := int(c-'A') + 1
retVal += v * int(math.Pow(26, float64(pos)))
pos--
}
return retVal
}
func titleToNumber1(s string) int {
retVal := 0
for i := 0; i < len(s); i++ {
retVal = retVal*26 + int(s[i]-'A'+1)
}
return retVal
}
// @lc code=end