Convert Excel Sheet Column Title to Number

Problem:

Given an excel sheet column title , convert it to the column value.

For example,

Column value of sheet number ‘A’ is 1

‘Z’ is 26

‘AA’ is 27

‘BA’ is 53 and so on.

Constraints:

• All the column letters are uppercase English letters
• The result value lies within the integer range in java

Try out the solution here;

https://leetcode.com/problems/excel-sheet-column-number/

Solution:

If it is a single letter we can return the value of it easily.

you just need to subtract the ascii value of the given letter with the ascii value of letter A and then add 1 to it.

```
theletter - 'A' + 1
```

For example if the letter is ‘A’ , then if you enter ‘A’ in ‘theletter’ variable you will get 1.

This is because the ascii value of A will be subtracted from the ascii value of A again resulting in zero to which we add 1.

Basically we want the integer value to start from 0 and then add 1 to it.

If there are two letters in the input , then all we have to do is multiply 26 to the previous letter and then add the current letter value to it.

For example if you take ‘BA’

The first letter value is 2.

Multiply it by 26, it gives 52 .

Now add the value of ‘A’ which is 1.

It gives 53 which is the answer.

This holds true for any number of digits.

All you have to do is multiply the previous letter value by 26 and then add the current letter value.

Do the above scanning each letter from left to right:

Here is the code:

```class Solution {
public int titleToNumber(String columnTitle) {

char[] array = columnTitle.toCharArray();

int result = 0;

for(int i=0;i<columnTitle.length();i++){

result *= 26;

result += ((array[i] - 'A') + 1) ;

}

return result;

}
}
```

Time complexity of the above code is O(n) since we scan each letter once.

Space complexity is O(1) since we are not using any extra space.

That’s it!

Posted

in

by

Tags: