171. Excel Sheet Column Number
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28分析:将字符串看做二十六进制表示的数据,
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 26 * 1 + 1 AB -> 26 * 1 + 2
...
ABC -> 26*26*1 + 26*2 + 3代码:
public class Solution {
public int titleToNumber(String s) {
int len = s.length();
int res = 0;
for(int i = 0; i < len; i++){
int temp = 1;
for(int j = len - i - 1; j > 0; j--){
temp *= 26;
}
res += temp * (s.charAt(i) - 'A' + 1);//String 的charAt(index)方法能将字符串的某一位作为字符型输出
}
return res;
}
}
168. 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分析:将上题中的分析过程反过来即可实现。
代码:
public class Solution {
public String convertToTitle(int n) {
String sb = "";
while(n / 26 != 0 || n % 26 != 0){
// 通过ASCII码确定所求字符,因为以字符'A'作为基准,n需要减一
char s = (char) ('A' + (n - 1) % 26);
// 求得的字符要加在高位
sb = s + sb;
n = (n - 1) / 26;
}
return sb;
}
}