LeetCode 171: Excel Sheet Column Number Solution

Master LeetCode problem 171 (Excel Sheet Column Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

171. Excel Sheet Column Number

Problem Explanation

Explanation:

To convert the Excel sheet column title to its corresponding column number, we can iterate through the characters in the title from right to left. At each step, we calculate the value of the current character and add it to the result by multiplying the previous result by 26. This is because there are 26 letters in the English alphabet. Finally, we return the accumulated result as the column number.

Algorithm:

  1. Initialize a variable result to 0.
  2. Iterate through the characters in the column title from right to left.
  3. At each step, calculate the value of the current character by subtracting 'A' from it and adding 1.
  4. Update the result by multiplying it by 26 and adding the value of the current character.
  5. Return the final result as the column number.

Time Complexity: O(n) where n is the length of the column title.

Space Complexity: O(1)

:

Solution Code

class Solution {
    public int titleToNumber(String columnTitle) {
        int result = 0;
        for (int i = 0; i < columnTitle.length(); i++) {
            int value = columnTitle.charAt(i) - 'A' + 1;
            result = result * 26 + value;
        }
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 171 (Excel Sheet Column Number)?

This page provides optimized solutions for LeetCode problem 171 (Excel Sheet Column Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 171 (Excel Sheet Column Number)?

The time complexity for LeetCode 171 (Excel Sheet Column Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 171 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 171 in Java, C++, or Python.

Back to LeetCode Solutions