码迷,mamicode.com
首页 > 其他好文 > 详细

Excel Sheet Column Number

时间:2015-01-13 14:16:34      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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 

public class Solution {
    public int titleToNumber(String s) {
        Map map = new HashMap();
        map.put(‘A‘, 1);
        map.put(‘B‘, 2);
        map.put(‘C‘, 3);
        map.put(‘D‘, 4);
        map.put(‘E‘, 5);
        map.put(‘F‘, 6);
        map.put(‘G‘, 7);
        map.put(‘H‘, 8);
        map.put(‘I‘, 9);
        map.put(‘J‘, 10);
        map.put(‘K‘, 11);
        map.put(‘L‘, 12);
        map.put(‘M‘, 13);
        map.put(‘N‘, 14);
        map.put(‘O‘, 15);
        map.put(‘P‘, 16);
        map.put(‘Q‘, 17);
        map.put(‘R‘, 18);
        map.put(‘S‘, 19);
        map.put(‘T‘, 20);
        map.put(‘U‘, 21);
        map.put(‘V‘, 22);
        map.put(‘W‘, 23);
        map.put(‘X‘, 24);
        map.put(‘Y‘, 25);
        map.put(‘Z‘, 26);
        
        char[] chars = s.toCharArray();
        int result = 0;
        for(int i = 0; i < chars.length; i++){
            int result_here = (Integer)map.get(chars[i]);
            for(int j = 0; j < chars.length - i -1; j++)
                result_here *= 26;
            result += result_here;
        }
        return result;
    }
}

其实就是26进制转为10进制。这里26进制不太严谨,因为并非0-25。

改进点,可以直接考虑字母代表的是进制数字就是s.charAt(i) - ‘A‘ + 1。而免去前面赋值的过程。

Excel Sheet Column Number

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4221005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!