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

自己的思路

十进制转“二十六进制”

public String convertToTitle(int n) {
 String str = "";
 do {
  int chrInt = n % 26;
  char chr;
  if (chrInt == 0) {
   chr = 'Z';
   n -= 26;
  } else {
   chr = (char) (chrInt - 1 + 'A');
  }
  str = chr + str;
  n = n / 26;
 } while (n != 0);
 return str;
}

别人的思路

public String convertToTitle(int n) {
    if(n <= 0){
        throw new IllegalArgumentException("Input is not valid!");
    }

    StringBuilder sb = new StringBuilder();

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

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

思路是一样的,但是代码更简洁,使用了StringBuilderreverse(),提前减 1 也避免了特殊处理’Z'

在算法问题中常常用到:

  • 1 的 ascii 为 33,十六进制为 21H
  • A 的 ascii 为 65,十六进制为 41H
  • a 的 ascii 为 97,十六进制为 61H