# 171 Excel Sheet Column Number

給一個excel的column title(英文字母),return對應的column number

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28

Concept:

AA = 1 + 26 = ('A' - 64)*26^0+('A' - 64)*26^1

AB = 2 + 26 = ('B' - 64)*26^0+('A' - 64)*26^1

Pseudocode:

for each character in s,

    if current character is out of the range of 'A' to 'Z', return 0

    ans += 26^(s.length()-i-1)* ('current character' - 'A' +1)

完整程式碼:

public class Solution {
    public int titleToNumber(String s) {
        //go through s from end of string
        //  read each character and -64 to get corresponding number
        //  ans += (length-i-1)*26+charAt(i)-64
        //**what if string is invalid?
        int ans=0;
        for(int i = s.length()-1; i >= 0; i--){
            char c = s.charAt(i);
            if((int)c < 65 || (int)c > 91) return 0;
            ans += Math.pow(26,(s.length()-i-1))*((int)c-64);
        }
        return ans;
    }
}

results matching ""

    No results matching ""