Leetcode[168, 171] Excel Sheet Column Title
14 Nov 2015###Task1 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
###Python
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
res = ''
dic = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
while n > 0:
res = dic[(n - 1) % 26] + res
n = (n - 1) / 26
return res
###Java
public class Solution {
public String convertToTitle(int n) {
if (n <= 0) {
return "";
}
StringBuilder res = new StringBuilder();
while (n > 0) {
if (n % 26 == 0) {
res.append('Z');
n = n / 26 - 1;
} else {
char crt = (char)('A' + n % 26 - 1);
res.append(crt);
n = n / 26;
}
}
return res.reverse().toString();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.convertToTitle(52));
}
}
###Points
- 二十六进制转化: like convert decimal to 26-scaled numerals
###Task1 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
###Python
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
ret = 0
for e in s:
ret = ret * 26 + ord(e) - ord('A') + 1
return ret
###Java
public class Solution {
public int titleToNumber(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] arr = s.toCharArray();
int res = 0;
for (int i = arr.length - 1; i >= 0; i--) {
int temp = (int)Math.pow(26, arr.length - 1 - i) * (arr[i] - 'A' + 1);
res += temp;
}
return res;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.titleToNumber("A"));
}
}
###Points
- 二十六进制转化: like convert decimal to 26-scaled numerals
- ord(‘a’) === ascii, chr(ascii) === char