LeetCode 171: Excel Sheet Column Number

MathString

Problem Description

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)

:

Solutions

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;
    }
}

Loading editor...