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].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
No comments:
Post a Comment