首页 > 其他 > 详细

Leetcode:Excel Sheet Column Title

时间:2015-02-18 17:41:10      阅读:304      评论: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 

思路:Because any_pos_int mod 26 should return a number in the interval [0, 25], but what we want is a number in the interval [1, 26]. Thus we have to shift the digit leftward by 1 which meansn-1.

实现代码:

class Solution {
public:
    string convertToTitle(int n) {
    string res="";
    while(n>0){
        res=char('A'+(n-1)%26)+res;
        n=(n-1)/26;
    }
        return res;
    }
};


java版本:

public class Solution {

    public String convertToTitle(int n) {
        StringBuilder result = new StringBuilder();

        while(n>0){
            n--;
            result.insert(0, (char)('A' + n % 26));
            n /= 26;
        }
        return result.toString();
    }
}



Leetcode:Excel Sheet Column Title

原文:http://blog.csdn.net/wolongdede/article/details/43877241

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