LeetCode-Excel Sheet Column Number/Title

171. 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:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 

很有意思的两个题目,满26进1,但是低位不清零。
如Z的下一个为AA,而不是A0
所以这就有点26进制数转10进制数的味道了。

package solutions._171;

/**
 * 171. Excel Sheet Column Number
 */
class Solution {
    public int titleToNumber(String s) {
        int num = 0;
        int k = s.length() - 1;
        for (char c : s.toCharArray()) {
            num += (c - 'A' + 1) * (int) Math.pow(26, k);
            k--;
        }
        return num;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.titleToNumber("BBA"));
        System.out.println(solution.titleToNumber("BA"));
        System.out.println(solution.titleToNumber("BCA"));
    }
}

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 

10进制转26进制

package solutions._168;

/**
 * 168. Excel Sheet Column Title
 */
class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            if (n % 26 == 0) {
                sb.append('Z');
                n = n / 26;
                n--;
            } else {
                sb.append((char) (n % 26 - 1 + 'A'));
                n = n / 26;
            }
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.convertToTitle(1405));
        System.out.println(solution.convertToTitle(53));
        System.out.println(solution.convertToTitle(1431));
        System.out.println(solution.convertToTitle(26));
        System.out.println(solution.convertToTitle(52));
        System.out.println(solution.convertToTitle(78));
    }
}

你可能感兴趣的:(leetcode题解)