LeetCode - 168 Excel Sheet Column Title

作者 QIFAN 日期 2016-09-02
LeetCode - 168 Excel Sheet Column Title

Difficulty:Easy

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开始,所以在每次给n赋值的时候需要减去1。

代码

public class Solution {
public String convertToTitle(int n) {
StringBuilder title = new StringBuilder();
n = n - 1;
while(n>=26) {
int mod = n % 26;
title.append((char)(mod + 'A'));
n = n / 26 - 1;
}
title.append((char)( n + 'A'));
return title.reverse().toString();
}
}

原题链接:https://leetcode.com/problems/excel-sheet-column-title/