【蓝桥杯】【Excel地址转换】

来源:互联网 发布:怎么加入网络主播 编辑:程序博客网 时间:2024/04/27 14:47

题目
Excel是最常用的办公软件。每个单元格都有唯一的地址表示。比如:第12行第4列表示为:“D12”,第5行第255列表示为“IU5”。
事实上,Excel提供了两种地址表示方法,还有一种表示法叫做RC格式地址。
第12行第4列表示为:“R12C4”,第5行第255列表示为“R5C255”。
你的任务是:编写程序,实现从RC地址格式到常规地址格式的转换。
【输入、输出格式要求】
用户先输入一个整数n(n<100),表示接下来有n行输入数据。
接着输入的n行数据是RC格式的Excel单元格地址表示法。
程序则输出n行数据,每行是转换后的常规地址表示法。
例如:用户输入:
2
R12C4
R5C255
则程序应该输出:
D12
IU5

分析
通过分析不难发现,问题的关键在于如何将列号码转换成字母,现在需要发现规律:
ABCDEFGHIJKLMNOPQRSTUVWXYZ 共26个英文字母
A~Z 1~26
AA~AZ 27~52
BA~BZ 53~78

HA~HZ 209~234
IA~IU 235~255
看实际的情况分析规律,假设列的号码是C:
1、如果C%26 == 0,再判断C/26的情况
2、如果C%26 != 0,再判断C/26的情况

源码

    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int line = sc.nextInt();        ArrayList<Cell> cellList = new ArrayList<Cell>();        //用List集合存储所有的RC对象        for(int i=0; i<line; i++){            String s = sc.next();            int r = s.indexOf('R');            int c = s.indexOf('C');            int row = Integer.valueOf(s.substring(r+1, c));            int column = Integer.valueOf(s.substring(c+1));            Cell cell = new Cell(row, column);            cellList.add(cell);        }        sc.close();        String s1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";        char[] c1 = s1.toCharArray();        for(int i=0; i<line; i++){            //sb代表列的英文字符编号            StringBuilder sb = new StringBuilder();            Cell cell = cellList.get(i);            int row = cell.getRow();            int column = cell.getCloumn();            int x = column % 26; //列号对26取模            int y = column / 26; //列号除以26            if(x == 0){                if(y == 1){                }else{                    sb.append(c1[y-2]);                }                sb.append('Z');            }else{                if(y == 0){                }else{                    sb.append(c1[y-1]);                }                sb.append(c1[x-1]);            }            sb.append(row);            System.out.println(sb);        }    }    //代表Excel的一个单元格    private static class Cell{        private int row;        private int cloumn;        public Cell(int row, int column){            this.row = row;            this.cloumn = column;        }        public int getRow() {            return row;        }        public void setRow(int row) {            this.row = row;        }        public int getCloumn() {            return cloumn;        }        public void setCloumn(int cloumn) {            this.cloumn = cloumn;        }    }