Excel Sheet Column Title & Excel Sheet Column Number

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 

注意,这题的数字不是从0开始,而是从1开始,我开始的时候用10进制的方式进行转换,发现不对。所以在程序里,用了n - 1.

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

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 

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

 

posted @ 2016-08-01 03:34  北叶青藤  阅读(304)  评论(0编辑  收藏  举报