171. Excel Sheet Column Number
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Base-26 number system where A=1, B=2, ..., Z=26 (no zero digit). Scan left to right: result = result * 26 + (char - "A" + 1).
Algorithm
- 1result = 0.
- 2For each character c: result = result * 26 + (c - 'A' + 1).
- 3Return result.
Example Walkthrough
Input: "ZY"
- 1.Z: 0*26+26=26. Y: 26*26+25=701.
Output: 701
Common Pitfalls
- •This is like converting a base-26 number but with digits 1 - 26 (not 0 - 25).
171.cs
C#
// Approach: Treat the column title as a base-26 number (A = 1…Z = 26),
// accumulating the result left to right with multiplication.
// Time: O(n) Space: O(1)
public class Solution
{
public int TitleToNumber(string columnTitle)
{
return columnTitle.Aggregate(0, (subtotal, c) => subtotal * 26 + (c - 'A' + 1));
}
}Advertisement
Was this solution helpful?