Accepted simple java solution and how to improve?


  • 3
    D
    public class Solution {
        public String convertToTitle(int n) {
            StringBuilder result = new StringBuilder();
    		while(n > 0) {
    			if(n % 26 == 0) {
    				result.append('Z');
    			} else {
    				result.append((char) ('A' + n%26 - 1));
    			}
    			n = (n - 1) / 26;
    		}
    		return result.reverse().toString();
        }
    }

  • 1
    W
    char *convertToTitle(int n) {
        int len=0;
        char *result;
    	int temp=n;
    	while(temp)
    	{
    		temp=(temp-1)/26;
    		len++;
    	};
    	result=(char *)malloc((len+1)*sizeof(char));
    	result[len]='\0';
        while(n)
        {
            result[--len]=(n-1)%26+'A';
            n=(n-1)/26;
        };
        return result;
    }`

  • 0
    D

    thank you! i also have this solution,do you have another solution with java ?


  • 0
    L
    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
    C

    public class Solution {

    public String convertToTitle(int n) {
        StringBuilder builder = new StringBuilder();
        while (n > 0) {
            char c = (char) ('A' + (n - 1) % 26);
            builder.append(c);
            n = (n - 1) / 26;
        }
        return builder.reverse().toString();
    }
    

    }


  • 0
    Y
    StringBuilder res = new StringBuilder();
    while (n > 0) {
    	n -= 1;
    	res.append((char) ('A' + (n % 26)));
    	n /= 26;
    }
    return res.reverse().toString();
    

    Hope to help.


Log in to reply
 

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