Question:
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
Thoughts:
Covert decimal number to 26th numeral system number.
Key point need to consider:
- If given number is a a multiple of 26, then
- modResult = modResult + 1
- quotient = quotient – 1
public class Solution { public String convertToTitle(int n) { //remove edge case if (n < 1) { return ""; } //use a string buffer to build final result StringBuffer sb = new StringBuffer(); while (n != 0) { int digit = n % 26; n = n / 26; //key point need to consider if (digit == 0) { digit = 26; n -= 1; } digit -= 1; char c = (char) (digit + 'A'); sb.append(c); } //because StringBuffer is built in reverse order //so reverse it to correct order sb.reverse(); return new String(sb); } }