Monday, March 28, 2016

LeetCode Q168: Excel Sheet Column Title

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 


Solution:
At the first glimpse, one may think this question as an one that convert decimal number to number with base 26. Unfortunately, it is not. the difference here is, there is no number represent 0 !!! The range here for each character is from [1, 26], not [0, 25].


class Solution {
public:
string convertToTitle(int _n) {
long n=_n;
string res;
int i=0;
while(n!=0){
int r = n%26;
r=r==0? 26:r;
char c = 'A'+r-1;
res = string(1, c)+res;
n = (n-r)/26;
}
return res;
}
};


Round 2 solution:
class Solution {
public:
string convertToTitle(int n) {
string res;
while(n!=0){
n=n-1;
res = string(1, (n%26 +'A')) + res;
n = n/26;
}
return res;
}
};
view raw Q168Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment