My C solution with runtime 0 ms (by using more space)


  • 0
    H

    Here is my solution.
    Welcome for discussing a simpler/scalable way with the same runtime.

    #include <stdio.h>
    #include <stdlib.h>
    char ret[7] = {0};   
    char* convertToTitle(int n) {
        int delta = 'A' - '1';    
    
    //error handling
    if (n < 1)
        return ret;
        
    //basic cases    
    if (n < 27) {
        ret[0] = ((char)(delta+n+'0'));   
        return ret;
    }
    
    //more than two digits
    int remain = 0;
    unsigned int data[8]={0};
    int index=0;
    data[0] = 1;
    
    // data[index] = 26^(index)
    for (index = 1; index < 8; index++){    	
        data[index] = (unsigned int)26*data[index-1];        
    }
    //from least significant to most significant digit
    int highest_digit=0;
    int the_digit=0;
    
    for (index = 0; index < 7; index++){
        //x_0
        remain = n % (data[index+1]);
        if(remain == 0)       
          remain = 26*data[index];
      the_digit = remain/data[index];  	
      n = n - the_digit*data[index];		
        //effective digit position
        if (the_digit !=0 )
            highest_digit = index;           		
        ret[index] = ((char)(delta+the_digit+'0'));   
    if(n <= 0){
    	printf("End index %d \n", index);
    	break;
    }
    		            
    }    
    
        int i=0;
        char temp='0';
        //reverse the order of effective digits
        for( i = 0; i < (highest_digit/2)+1; i++){
            temp = ret[i];
            ret[i] = ret[highest_digit-i];
            ret[highest_digit-i] = temp;
        }        
        return ret;        
    }

Log in to reply
 

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