1.문제
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
영어 알파벳으로 이루어진 columnTitle 이라는 문자열이 주어질 때 주어진 규칙대로 대응하는 숫자를 리턴하는 문제이다.
Example 1
Input: columnTitle = "A"
Output: 1
Example 2
Input: columnTitle = "AB"
Output: 28
Example 3
Input: columnTitle = "ZY"
Output: 701
Constraints:
- 1 <= columnTitle.length <= 7
- columnTitle consists only of uppercase English letters.
- columnTitle is in the range ["A", "FXSHRXW"].
2.풀이
- 문자열에서 단위가 올라갈 때 마다 26 의 단위 수가 올라간다.
/**
* @param {string} columnTitle
* @return {number}
*/
const titleToNumber = function (columnTitle) {
let length = columnTitle.length;
let result = 0;
for (let i = 0; i < columnTitle.length; i++) {
// 각 단어 자리수에 맞게 계산을 하여 더해준다.
result += (columnTitle[i].charCodeAt() - 64) * 26 ** (length - 1);
length--;
}
return result;
};
3.결과
