[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 

思路:

和168题是互逆的,从26进制转10进制
s.charAt(i)-'A'是为了算出s中第i位对应的相对值
可以省去强制转化(int)类型

 1 public class Solution171 {
 2     public int titleToNumber(String s) {
 3         int sum = 0;
 4         for(int i = 0; i < s.length();i++){
 5             sum = 26 * sum + s.charAt(i) - 'A'+1;            
 6         }    
 7         return sum;
 8     }
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         Solution171 solution171 = new Solution171();
12         String s = "AB";
13         System.out.println(solution171.titleToNumber(s));
14     }
15 
16 }

 

posted @ 2018-01-04 17:11  zlz099  阅读(154)  评论(0编辑  收藏  举报