[leetcode]excel sheet column number/title

Excel Sheet Column Title

题目描述

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1
2
3
4
5
6
7
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB

代码

其实就是26进制转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class {
public String convertToTitle(int n) {
if(n < 1) return "";
StringBuilder sb = new StringBuilder();

while(n > 0){
n--;
sb.append((char)('A' + n % 26));
n = n / 26;
}

return sb.reverse().toString();
}

}

不在最后反转就用前插函数

1
2
3
4
5
6
7
8
9
10
11
12
13
public class {
public String convertToTitle(int n) {
StringBuilder result = new StringBuilder();

while(n>0){
n--;
result.insert(0, (char)('A' + n % 26));
n /= 26;
}

return result.toString();
}
}

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:

1
2
3
4
5
6
7
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class  {
public int titleToNumber(String s) {

// int sum = 0;
// s = s.toUpperCase();
// for(int i = 0; i < s.length(); i++){
// int digit = s.charAt(i) - 'A' + 1;
// sum = sum + digit*(int)Math.pow(26,s.length()-(i+1));
// }
// return sum;
if(s == null || s.length() == 0) return 0;
int sum = 0;
for(int i = 0; i < s.length(); i++){
sum = sum * 26 + (s.charAt(i) - 'A' + 1);
}
return sum;
}
}