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;
        }
    }
  • 相关阅读:
    精读大道至简01
    mysql查询语句出现sending data耗时解决
    定位线上问题
    docker命令
    .net core2学习笔记
    centos下安装色彩scrapy
    mysql中id值被重置的情况
    MySql中的SHOW INDEX 查出的结果列代表的意义
    ELK安装
    使用PowerDesigner进行面向对象分析与UML建模(转)
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4515165.html
Copyright © 2011-2022 走看看