zoukankan      html  css  js  c++  java
  • LeetCode--Excel Sheet Column Title

    Given a positive integer, return its corresponding column title as appear in an Excel sheet.

    For example:

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

    问题描述:给出一个正整数,计算它对应的Excel列标。
    问题分析:题目可以转化为一个十进制转化为二十六进制的计算。但是略有不同,因为计算是从1开始。所有有小细节需要注意,代码如下:注意之处在代码中标识。
    public class Solution {
        public String convertToTitle(int n) {
             HashMap<Integer, Character> h = new HashMap<Integer, Character>();
            h.put(1, 'A');
            h.put(2, 'B');
            h.put(3, 'C');
            h.put(4, 'D');
            h.put(5, 'E');
            h.put(6, 'F');
            h.put(7, 'G');
            h.put(8, 'H');
            h.put(9, 'I');
            h.put(10, 'J');
            h.put(11, 'K');
            h.put(12, 'L');
            h.put(13, 'M');
            h.put(14, 'N');
            h.put(15, 'O');
            h.put(16, 'P');
            h.put(17, 'Q');
            h.put(18, 'R');
            h.put(19, 'S');
            h.put(20, 'T');
            h.put(21, 'U');
            h.put(22, 'V');
            h.put(23, 'W');
            h.put(24, 'X');
            h.put(25, 'Y');
            h.put(26, 'Z');
            
            ArrayList<Character> l = new ArrayList<Character>();
            while(n>0){
                int t = n%26; //余数t的范围只能是在0-25之间,因此如果t为0,说明该位置对应的值为‘Z’,同时高位减一。
                n = n/26;
                if(t==0){ //余数为0,插入‘Z’,高位减一
                    l.add('Z');
                    n--;
                }else{
                    l.add(h.get(t));
                }
            }
            char[] c = new char[l.size()]; //反转
            for(int i=l.size()-1; i>=0; i--){
                c[l.size()-i-1] = l.get(i);
            }
            String s = new String(c);
            return s;
        }
    }
  • 相关阅读:
    leetcode 268. Missing Number
    DBSCAN
    python二维数组初始化
    leetcode 661. Image Smoother
    leetcode 599. Minimum Index Sum of Two Lists
    Python中的sort() key含义
    leetcode 447. Number of Boomerangs
    leetcode 697. Degree of an Array
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月3日)
    北京Uber优步司机奖励政策(1月2日)
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4515165.html
Copyright © 2011-2022 走看看