leetcode 171. Excel Sheet Column Number

Related to question Excel Sheet Column Title

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 
水题。

package leetcode;

public class Excel_Sheet_Column_Number_171 {

	public int titleToNumber(String s) {
		int result=0;
		char[] chars=s.toCharArray();
		int power=0;
		for(int i=chars.length-1;i>=0;i--){
			int the=chars[i]-'A'+1;
			result=result + (int)Math.pow(26,power)*the;
			power++;
		}
		return result;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Excel_Sheet_Column_Number_171 e=new Excel_Sheet_Column_Number_171();
		System.out.println(e.titleToNumber("AB"));
	}

}
我的解法亦可,下面大神的解法亦可。

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

你可能感兴趣的:(leetcode,leetcode)