[LeetCode] 168. Excel Sheet Column Title + 171. Excel Sheet Column Number

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"

因为字母是26进制的,所以当我们看到一个数字的时候,我们会很自然地想到去mod26然后转换成字母。但是因为26个字母对应的数字是1-26而不是0-25所以需要记得先减去1才能做转换的动作。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public String convertToTitle(int n) {
 3         StringBuilder sb = new StringBuilder();
 4         while (n > 0) {
 5             n--;
 6             sb.append((char)('A' + n % 26));
 7             n /= 26;
 8         }
 9         return sb.reverse().toString();
10     }
11 }

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

Constraints:

  • 1 <= s.length <= 7
  • s consists only of uppercase English letters.
  • s is between "A" and "FXSHRXW".

Excel表列序号。题意是给了一个excel表列的序号,请转换成阿拉伯数字。

因为字母是每26个循环一次,所以相当于26进制,每26个数则向前进一位。同时注意因为A代表1,所以每个字母跟A做减法的时候还需额外 + 1。

时间O(n)

空间O(1)

Java实现

1 class Solution {
2     public int titleToNumber(String s) {
3         int res = 0;
4         for (int i = 0; i < s.length(); i++) {
5             res = res * 26 + (s.charAt(i) - 'A' + 1);
6         }
7         return res;
8     }
9 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13473149.html