# 168 Excel Sheet Column Title
給一個integer,求Excel Column的英文字母title。
Concept:
觀察一下
1 -> A
27 -> AA
28 -> AB
28 % 26 = 2 -> B
(27 - 2)/26 = 1
1 % 26 = 1 -> A
(1 - 1)/26 = 0 -> done.
Pseudocode:
use a stringbuilder sb to build column title
declare 2 int variable, division = and carry
while if n > 0
char c = 65+(n%26)-1
sb.append(c)
carry = n % 26
n = n / 26
sb.append(carry)
return sb.reverse().toString
**notice: edge case-> 26
完整程式碼:
public class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
int carry;
if(n==0) return "";
while(n>0){
carry = n % 26;
if(carry==0) carry = 26;
char c = (char)(65+carry-1);
sb.append(c);
n = (n-carry)/26;
}
return sb.reverse().toString();
}
}