Sunday, December 28, 2014

Excel Sheet Column Title (LeetCode Math)

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

Idea: This is a decimal to 26cimal problem. The 26cimal is denoted as 1,2,...,26, algebraically the same as using 0,1,...,9 to denote decimal.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public String convertToTitle(int n) {  
     StringBuilder builder=new StringBuilder();  
     while(n!=0)  
     {  
       builder.insert(0,(char)((n-1)%26+'A'));  
       n=(n-1)/26;  
     }  
     return builder.toString();  
   }  
 }  

No comments:

Post a Comment