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
Idea: Actually it is a special 26cimal (may be a wrong word?) to decimal problem, e.g. AB-> ('A'- 'A'+1 )*26 + ('B' - 'A'+1) -> 28. The 26cimal is denoted as 1,2,...,26, algebraically the same as using 0,1,...,9 to denote decimal.
Time: O(n) Space: O(1)
Code:
public class Solution {
public int titleToNumber(String s) {
int sum=0;
for(int i=0;i<s.length();i++)
{
int val=(int)(s.charAt(i)-'A'+1);
sum=sum*26+val;
}
return sum;
}
}
No comments:
Post a Comment