技巧是:利用char 'Z'和'A'对应ASCII的值
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
...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"
class Solution {
public String convertToTitle(int n) {
int letterLen = (int)'Z' - (int)'A'+1;
int a = (int)'A';
StringBuffer sb = new StringBuffer();
while(n > 0 ){
n--;
char c =(char)(a + n%letterLen );
sb.append(c);
n /=letterLen;
}
return sb.reverse().toString();
}
}
171. Excel Sheet Column Number
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
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
class Solution {
public int titleToNumber(String s) {
char[] c = s.toCharArray();
int result = 0;
for(int i = 0 ; i < c.length;i++){
result = result*26 + c[i] - 'A'+1 ;
}
return result;
}
}
网友评论