题目158:
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
class Solution {
public String convertToTitle(int n) {
//给定整数,求其Excel表达
String res="";
while(n>0){
n--;
char c=(char)('A'+n%26);
res=String.valueOf(c)+res;
n/=26;
}
return res;
}
}
题目171:
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
class Solution {
public int titleToNumber(String s) {
//给定字符串,给出其整数表达
//类型于26进制(注意对应字母所在位置,需要加上其后面位数*25)
char [] ch=s.toCharArray();
int sum=0;
for(int i=0;i<ch.length;i++){
int temp=ch[i]-'A'+1;
sum+=temp*Math.pow(26,ch.length-1-i);
}
return sum;
}
}