Leetcode:Excel Sheet Column Title

来源:互联网 发布:linux dns配置 编辑:程序博客网 时间:2024/06/05 05:26

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();    }}



0 0
原创粉丝点击