171.Excel Sheet Column Number

Description

这里记录进制问题集合,非常简单,长期更新

  1. 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
  2. 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

Solution

[leetcode 171] Excel Sheet Column Number

很简单,就当成进制问题就可以了,然后一个递归就解决了:

1
2
3
4
5
6
7
8
9
10
public int titleToNumber(String s) {
int n=s.length();
int res=0;
return getNumber(n,s);
}
private int getNumber(int n, String s) {
if(n==0)return 0;
return (int)((s.charAt(0)-'A'+1)*Math.pow(26,n-1)+getNumber(n-1,s.substring(1)));
}

[leetcode 168] Excel Sheet Column Title

也是递归问题,将大问题转小问题,这里取余的时候需要考虑除数的问题(26的问题)

1
2
3
4
5
6
7
8
9
10
11
12
public String convertToTitle(int n) {
String res="";
return getColumn(res,n);
}
private String getColumn(String res, int n) {
if(n==0)return res;
if(n%26==0){res='Z'+res;n=n/26-1;}
else {res=(char)('A'+n%26-1)+res;n=n/26;}
res=getColumn(res,n);
return res;
}

如果觉得有帮助,给我打赏吧!