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