LeetCode – Excel Sheet Column Number (Java)

Problem

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 
    ...
    AAA -> 703 

Java Solution

This problem is related to Excel Sheet Column Title.

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

This solution is provided by Akhil Mittal.

4 thoughts on “LeetCode – Excel Sheet Column Number (Java)”

  1. More concise with run time of 1ms:
    public int titleToNumber(String s) {
    int result = 0;
    for (char c : s.toCharArray()) {
    result = result * 26 + (c - 'A') + 1;
    }
    return result;
    }

  2. I think this is a little bit more simple

    public class Solution {
    public int titleToNumber(String s) {
    int n = s.length();
    int res = 0;
    for(int i = n-1; i >=0; i--){
    res+=Math.pow(26,n-i-1)*(s.charAt(i)-64);
    }
    return res;
    }
    }

  3. result = result + (int) Math.pow(26, t) * (curr-‘A’+1);

    I think instead of multiplication we need addition here

    result = result + (int) Math.pow(26, t) + (curr-‘A’+1);

  4. more simple solution, I think

    def strToCol(string):
    res = 0
    for symbol in string.lower():
    res = res * 26 + ord(symbol) – ord(‘a’) + 1
    return res

Leave a Comment