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
1) n reminder得到1-26对应字母位置,但是A是第一位(1),所以n--先退一位然后加到A上
2) 每个循环结束,甩掉该循环,n/26
public class Solution {
// http://www.danielbit.co/blog/puzzle/leetcode/leetcode-excel-sheet-column-titlepublic String convertToTitle(int n) {
StringBuilder re = new StringBuilder();
while(n>0){
n--;
char ch = (char)(n%26 + 'A');
n = n/26;
re.append(ch);
}
re.reverse();
return re.toString();
}
}
反過來題目則簡單的多
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
public class Solution {
public int titleToNumber(String s) {
int res=0;
if(s==null||s.length()<=0) return 0;
int n = s.length();
int i=0;
while(i<n){
int tmp = (s.charAt(i)-'A'+1);
res = res*26+tmp;
i++;
}
return res;
}
}