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

[leetcode]Excel Sheet Column Title

时间:2014-12-28 10:29:31      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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 

基本思路:

此题乍一看,很简单,但程序一次通过却不容易,有一些容易忽略的点。(结合程序来说) 如对Z的处理,用map保存时,它对26的余数应该是0。  而且还要注意对n进行更新时,n = n/26是错误的。也是因为当n = 26时 就不需要进入下轮循环了。

代码:

public String convertToTitle(int n) {  //java
        Map<Integer,Character> map = new HashMap<Integer,Character>();
        for(int i = 1; i<= 26; i++){
            Integer key = i%26;
            Character value = (char)(64+i);
            map.put(key,value);
            
        }
        
        String result = "";
        while(n!=0){
            int tmp = n%26;
            result = map.get(tmp) + result;
            n = (n-1)/26;
        }
        return result;
        
    }


[leetcode]Excel Sheet Column Title

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/42211819

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