Practise it on judges as “Excel Sheet Column Number”.
In plain words
Spreadsheet columns count A to Z, then AA, AB, … It is like counting in base 26 where A = 1 and Z = 26. Read the letters left to right; each new letter shifts the value so far by one place (× 26) and adds its own value, just like reading 3, then 37, then 375 in base 10.
Return the column number. Example: "ZY" → 701.
The problem
Convert a column title (A = 1, Z = 26, AA = 27, …) to its number.
Example 1
Input: columnTitle = "ZY"
Output: 701
Constraints
1 ≤ length ≤ 7
Pattern clues in the wording
→ Letters as digits
These clues point to Number Theory and Combinatorics: GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.
Stuck? Take one hint at a time
Solution · starter
class Solution {
public int titleToNumber(String columnTitle) {
return 0;
}
}
Write your solution locally or in your editor for now. Pick Java, Python, C++, JavaScript or Go above: every solution on this page switches with it. The in-browser runner will run these tests right here.
▶ Dry run: value = value × 26 + lettercolumnTitle = "ZY"
Z
0
Y
1
vars(vars)
value: 0
Step 1/3Start with 0.
Approach 1
class Solution {
public int titleToNumber(String columnTitle) {
int value = 0;
for (char c : columnTitle.toCharArray()) value = value * 26 + (c - 'A' + 1);
return value;
}
}