题目:
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
解题思路:
进制转换问题,26进制
从后往前遍历生成,这里要注意是从1开始的,而不是从0开始,所以需要减一
代码:
class Solution {
public String convertToTitle(int n) {
//进制转换--26进制
//从低到高生成
String res = "";
while(n>0){
//由于下标从1开始而不是从0开始,因此要减一操作
res = (char)((n-1)%26+'A')+res;
n = (n-1)/26;
}
return res;
}
}
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
解题思路:
26进制转化:前面的数+当前位上的数=最后结果(十进制表示)
代码:
class Solution {
public int titleToNumber(String s) {
//26进制转换
//前面的数*26+当前位上的数=当前数(十进制)
int res=0;
for(int i=0;i<s.length();i++){
int temp = s.charAt(i)-'A'+1;//从1开始
res = res*26+temp;
}
}
}