Accepted C Solution the code is quite long but not tricky


  • 0
    R
    char* intToRoman(int num) {
    	// max length would be 15+1,reprents 3888
    	char buf[16]={0};
    	char *p=buf;
    	int ele=1000;
    
    	while(ele>0){
    		int digit=num/ele;
    		num%=ele;
    		if(digit>0){
    			switch(ele){
    				case 1000:
    					while(digit>0){
    						*p++='M';
    						--digit;
    					}
    					break;
    				default:{
    					char one;
    					char five;
    					char ten;
    					switch(ele){
    						case 100:
    							one='C';
    							five='D';
    							ten='M';
    							break;
    						case 10:
    							one='X';
    							five='L';
    							ten='C';
    							break;
    						case 1:
    							one='I';
    							five='V';
    							ten='X';
    							break;
    					}
    					switch(digit){
    						case 9:
    							*p++=one;
    							*p++=ten;
    							break;
    						case 4:
    							*p++=one;
    							*p++=five;
    							break;
    						default:
    							if(digit>=5){
    								*p++=five;
    								digit-=5;
    							}
    							while(digit>0){
    								*p++=one;
    								--digit;
    							}
    							break;
    					}
    
    						}
    				break;//end of default
    			}
    		}
    		ele/=10;
    	}
    
    
    	char *ret=malloc(sizeof(char)*(p-buf+1));
    	strcpy(ret,buf);
    
    	return ret;
    }
    

    iterating and converting.quite simple~


Log in to reply
 

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