Excel Sheet Column Number

Problem

Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28

Solution

My original solution calculating from the last position

public class Solution {
    public int titleToNumber(String s) {
        int res = 0, times = 1;
        for (int i = s.length() - 1; i >= 0; i--) {
            int value = s.charAt(i) - 'A' + 1;
            res += value * times;
            times *= 26;
        }
        return res;
    }
}

More concise version calculating from the first position

public class Solution {
    public int titleToNumber(String s) {
        int res = 0;
        for (char ch : s.toCharArray()) res = res * 26 + ch - 'A' + 1;
        return res;
    }
}

Analysis

This is a typical problem about converting numbers
The second solution is concise and very straightforward

Complexity:

  • Time: O(n), linear time complexity
  • Space: O(1), only constant space is used

results matching ""

    No results matching ""