首页 > 其他 > 详细

Leetcode Excel Sheet Column Title

时间:2015-09-30 00:56:23      阅读:230      评论:0      收藏:0      [点我收藏+]

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= 26 的边界情况。我的代码分情况讨论,参考代码很巧妙,用n--

The key is n--. The minimum in 26-bit number is mapped to 1, not 0.


Java code:

1.

 public String convertToTitle(int n) {
        if(n < 1) {
            return "";
        }
        StringBuilder s = new StringBuilder();
        char a = ‘A‘;
        while(n >= 1) {
            int x = n%26;
            if( x == 0) {
                a = ‘Z‘;
                n = n/26 - 1;
            }else {
                a = (char)(‘A‘ + x - 1);
                n = n/26;
            }
            s.append(a);
        }
        return s.reverse().toString();
    }

2. 参考代码,更好。

public String convertToTitle(int n) {
        if(n <= 0){
            throw new IllegalArgumentException("Input is not valid!");
        }
     
        StringBuilder sb = new StringBuilder();
     
        while(n > 0){
            n--;
            char ch = (char) (n % 26 + ‘A‘);
            n /= 26;
            sb.append(ch);
        }
        return sb.reverse().toString();
    }

Reference:

1. http://www.programcreek.com/2014/03/leetcode-excel-sheet-column-title-java/

 

Leetcode Excel Sheet Column Title

原文:http://www.cnblogs.com/anne-vista/p/4847679.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!