leetcode 171. Excel Sheet Column Number

1082 단어 leetcode
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;
}

좋은 웹페이지 즐겨찾기