Share my code with c 1ms


  • 3
    D
    char *convertToTitle(int n) {
        int char_size = 0, num = n, i = 1;
    	char *result;
    	while(num > 0) {
            num = (num - 1) / 26;
            char_size++;
        }
    	result = (char *) malloc(char_size*sizeof(char));
        while(n > 0) {
    		if(n % 26 == 0) {
    			*(result + char_size - i) = 'Z';
    		} else {
    			*(result+char_size-i) = (char)('A' + n%26 - 1);
    		}
    		n = (n - 1) / 26;
    		i++;
    	}
    	return result;
    }

  • 3
    I

    you can do better.

    char *convertToTitle(int n) {
    int char_size = 0, num = n;
    char *result;
    while(num > 0) {
        num = (num - 1) / 26;
        char_size++;
    }
    result = (char *) malloc(char_size*sizeof(char));
    while(n > 0) {
        char_size--;
        if(n % 26 == 0) {
            *(result + char_size) = 'Z';
        } else {
            *(result+char_size) = 64 + n%26;
        }
        n = (n - 1) / 26;
    }
    return result;
    

    }


  • -1
    F

    you can do better.

    string convertToTitle(int n) {
          const int len = 10;
          char str[len];
          str[len-1] = 0;
          int a;
          int i = len;
          while (n--) {
                a = n%26;
                n /= 26;
                str[--i] = a+'A';
           }
           return string(str+i, len-i);
    }

  • 0
    M

    my solution, quite similar

    char* convertToTitle(int n) {
        int char_size = 0, tmp = n;
        while(tmp--) {
            tmp /= 26; 
            char_size++; 
        }
        char* ans = (char *)calloc(char_size, sizeof(char));
        while(n--){
            ans[--char_size] = (char)(n%26+'A');
            n /= 26;
        }
        return ans;
    }

Log in to reply
 

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