Excel Sheet Column Number
Problem
Given a string columnTitle (the column label in an Excel sheet), return its corresponding column number.
columnTitle = "ZY"701def title_to_number(s):
n = 0
for c in s:
n = n * 26 + (ord(c) - ord('A') + 1)
return n
function titleToNumber(s) {
let n = 0;
for (const c of s) {
n = n * 26 + (c.charCodeAt(0) - 64);
}
return n;
}
class Solution {
public int titleToNumber(String s) {
int n = 0;
for (int i = 0; i < s.length(); i++) {
n = n * 26 + (s.charAt(i) - 'A' + 1);
}
return n;
}
}
int titleToNumber(string s) {
int n = 0;
for (char c : s) {
n = n * 26 + (c - 'A' + 1);
}
return n;
}
Explanation
Excel column labels are just numbers written in base 26, where the digits are the letters A-Z. We decode the string the same way you read a normal number: process letters left to right, building up the value as we go.
Each letter is worth its position in the alphabet: A=1, B=2, ..., Z=26. In code that is ord(c) - ord('A') + 1. Notice there is no zero — this is a bijective base-26 system, so A is 1 rather than 0.
For every letter we do n = n * 26 + value. Multiplying by 26 shifts the previous total one place to the left (just like multiplying by 10 in decimal), then we add the new letter's value.
Example: "ZY". Start n = 0. Z is 26, so n = 0 * 26 + 26 = 26. Then Y is 25, so n = 26 * 26 + 25 = 701. The answer is 701.
We touch each character once, so the work is proportional to the length of the label.