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
public class Solution { public int titleToNumber(String s) { // BAC -> 2*26*26+1*26+3 // Note: Character.getNumericValue(ch) is used for convert number (e.g, '3' -> 3) // (int) is used to get ASCII code (e.g., 'A' -> 65; '3' -> 51) int n = s.length(); int result = 0; int nA = 'A'; for (int i = n-1; i >= 0; i--) result += Math.pow(26, n-i-1)*(s.charAt(i)-nA+1); return result; } }
No comments:
Post a Comment