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进制问题,所以问题主要在于如何区分开"A" 和 “Z”的情况。因为这是26进制,每次我们都需要除去26,这时候我们需要分辨“1”是因为余数产生(这时候是A),还是因为商而产生(这时候是Z)。
所以引入一个负1到计算中去,这样就可以把余数和商区分开来。
class Solution {
public String convertToTitle(int n) {
String res = "";
int remain = 0;
while(n != 0){
remain = (n-1) % 26;
n = (n-1) / 26;
res += (char)(remain + 65);
}
return new StringBuilder(res).reverse().toString();
}
}