Here is my Java solution. Similar to the number to title.
public int titleToNumber(String s) {
int result = 0;
for(int i = 0 ; i < s.length(); i++) {
result = result * 26 + (s.charAt(i) - 'A' + 1);
}
return result;
}
This is neat. I looped from the end, had to use Math.pow(). Which seems unnecessary after looking at your solution.
public class Solution {
public int titleToNumber(String s) {
int result = 0;
for (int i = s.length() - 1, j = 0; i >= 0; i--, j++)
result += Math.pow(26, j) * (s.charAt(i) - 'A' + 1);
return result;
}
}
@rainhacker I did it just like you. Do you think calling power is not as efficient as the darko1002001's algorithm?
@darko1002001 yes,you did't use Math.pow(),that's great! this is my code:
public class Solution {
public int titleToNumber(String s) {
s=s.toUpperCase();
int count=0;
int len=s.length();
for(int i=0;i<len;i++){
int curr=s.charAt(i)-64;
count+=Math.pow(26,len-i-1)*curr;
}
return (int)count;
}
}