Do as "mod and divide by 26"; the only trick is to handle case of reminder == 0


  • 0
    B

    Do the mod and divide 26 in a while loop, the only trick is to handle a special case when reminder was 0:

    public String convertToTitle(int n) {
        StringBuffer sb = new StringBuffer();
        while(n > 0){
            int reminder = n % 26;
            n /= 26;
            if(reminder == 0){
                sb.insert(0, 'Z');
                n--;
            }else
                sb.insert(0, (char)('A' + reminder - 1));
        }
        return sb.toString();
    }

  • 1
    L

    How about this:

    public class Solution {
        public String convertToTitle(int n)
        {
            final StringBuilder sb = new StringBuilder();
            
            for (; n != 0; n /= 26)
            {
                sb.insert(0, (char)(--n % 26 + 'A'));
            }
            
            return sb.toString();
        }
    }

  • 0
    D

    Awesome. Nice way of converting 1 based remainder to 0 based.


Log in to reply
 

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