0 ms Java Solution with character map.


  • 1
    V
        /**
           1. Idea is same as converting decimal integer to binary using stack.
           2. Only trick is the n - 1 and Z at 0 index. N - 1 at last is required because column number is starting from 1 instead of 0. 
           3. Use of stack is eliminated by appending result at last of new character.
           4. Use or character array can be eliminated but using it makes the solution straightforward and easy to understand. 
        */    
        public String convertToTitle(int n) {
                String result = "";
                char[] map = {'Z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y'};
                while(n > 0 ){
                    result =   map[n % 26] + result ;
                    n = ( n - 1) / 26; // minimum is 1 not 0. Hence n - 1 is required
                } 
                return result;
            }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.