-
Notifications
You must be signed in to change notification settings - Fork 2
/
171.excel表列序号.js
72 lines (68 loc) · 1.22 KB
/
171.excel表列序号.js
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
/*
* @lc app=leetcode.cn id=171 lang=javascript
*
* [171] Excel表列序号
*
* https://leetcode-cn.com/problems/excel-sheet-column-number/description/
*
* algorithms
* Easy (68.41%)
* Likes: 185
* Dislikes: 0
* Total Accepted: 54.9K
* Total Submissions: 80.3K
* Testcase Example: '"A"'
*
* 给定一个Excel表格中的列名称,返回其相应的列序号。
*
* 例如,
*
* A -> 1
* B -> 2
* C -> 3
* ...
* Z -> 26
* AA -> 27
* AB -> 28
* ...
*
*
* 示例 1:
*
* 输入: "A"
* 输出: 1
*
*
* 示例 2:
*
* 输入: "AB"
* 输出: 28
*
*
* 示例 3:
*
* 输入: "ZY"
* 输出: 701
*
* 致谢:
* 特别感谢 @ts 添加此问题并创建所有测试用例。
*
*/
// @lc code=start
/**
* @param {string} s
* @return {number}
*/
var titleToNumber = function(s) {
const charCodeBase = 'A'.charCodeAt(0) - 1;
const n = s.length;
let number = 0;
/*
* Think of it as base 26. For example,
* Column number of "AB" = 1 * 26^1 + 2 * 26^0
*/
for (let i = 0; i < n; i++)
number += (s.charCodeAt(i) - charCodeBase) * Math.pow(26, n-i-1);
return number;
};
// @lc code=end