Tuesday, April 14, 2015

168. Excel Sheet Column Title Leetcode Java

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 
Solution:
Related to 171. Excel Sheet Column Number
It is a very simple problem, It is just to transform a decimal number to a 26 based number.Just like how we did for transferring from decimal to binary or hexadecimal number. 
 public String convertToTitle(int n) {  
   if(n<=0) return "";  
   StringBuilder sb=new StringBuilder();  
   while(n>0){  
     sb.append((char)('A'+(n-1)%26));  
     n=(n-1)/26;  
   }  
   return sb.reverse().toString();  
   }  

No comments:

Post a Comment