Excel Sheet Column Number LeetCode Solution

Last updated on October 5th, 2024 at 09:08 pm

Here, We see Excel Sheet Column Number LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Math

Companies

Microsoft, Uber

Level of Question

Easy

Excel Sheet Column Number LeetCode Solution

Excel Sheet Column Number LeetCode Solution

Problem Statement

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example:A -> 1 B -> 2 C -> 3 … Z -> 26 AA -> 27 AB -> 28 …

Example 1:
Input: columnTitle = “A”
Output: 1

Example 2:
Input: columnTitle = “AB”
Output: 28

Example 3:
Input: columnTitle = “ZY”
Output: 701

1. Excel Sheet Column Number Leetcode Solution C++

class Solution {
public:
    int titleToNumber(string columnTitle) {
        int result = 0;
        for(char c : columnTitle)
        {
            int d = c - 'A' + 1;
            result = result * 26 + d;
        }
        return result;
    }
};

2. Excel Sheet Column Number Leetcode Solution Java

public class Solution {
    public int titleToNumber(String columnTitle) {
        if (columnTitle == null) return -1;
        int sum = 0;
        for (char c : columnTitle.toUpperCase().toCharArray()) {
            sum *= 26;
            sum += c - 'A' + 1;
        }
        return sum;
    }
}

3. Excel Sheet Column Number Solution JavaScript

var titleToNumber = function(columnTitle) {
    const charCodeBase = 'A'.charCodeAt(0) - 1;
    const n = columnTitle.length;
    let number = 0;
    for (let i = 0; i < n; i++)
        number += (columnTitle.charCodeAt(i) - charCodeBase) * Math.pow(26, n-i-1);
    return number;
};

4. Excel Sheet Column Number Solution Python

class Solution(object):
    def titleToNumber(self, columnTitle):
            corresponding_number = 0
            for i in range(len(columnTitle)):
                current_letter=columnTitle[i]
                corresponding_letter_value=ord(current_letter) - ord('A') + 1
                corresponding_number += (corresponding_letter_value *pow(26,len(columnTitle)-i-1))
            return corresponding_number
Scroll to Top