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
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.
算法分析: 一眼就能看出来这是一个10进制转化为26进制的算法了.
顺便贴上各个语言版本的运行效率.
Java:
public class Solution {
public String convertToTitle(int n) {
char c = '0';
int mod = 0;
String str = "";
while(n > 0) {
mod = n % 26;
n = n / 26;
if (mod == 0) {
c = 'Z';
n--;
}
else
c = (char)(mod - 1 + (int)'A');
str = c + str;
}
return str;
}
}
C++:
class Solution {
public:
string convertToTitle(int n) {
char c = '0';
string str = "";
int mod = 0;
while (n > 0) {
mod = n % 26;
n /= 26;
if (mod == 0) {
c = 'Z';
n--;
} else
c = mod - 1 + 'A';
str = c + str;
}
return str;
}
};
Python:
class Solution:
# @return a string
def convertToTitle(self, num):
c = ''
str = ''
mod = 0
while (num > 0):
mod = num % 26
num /= 26
if (mod == 0):
num = num - 1
c = 'Z'
else:
c = (chr)(ord('A') + mod - 1)
str = c + str
return str
继续查看有关 日志连载的文章
0个访客评论