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.

Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Akhil Mittal

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

• Carla Flores

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

• Andre

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