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

Leetcode:Excel Sheet Column Title

时间:2015-02-18 17:41:13      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:excel sheet column t

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

标签:excel sheet column t

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

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