C implementation


  • 0
    D

    Any thoughts?

    int getWholeNumber(char *input) {
    	char *beg = input;
    	int retVal = 0;
    	if(*beg == '-') {
    		beg++;
    	}
    	while(*beg >= '0' && *beg <= '9') {
    		beg++;
    	}
    	int tensCounter = 0;
    	while(beg != input) {
    		beg--;
    		if(*beg == '-') {
    			retVal *= -1;
    		} else {
    			retVal += (*beg-'0') * pow(10, tensCounter);
    		}
    		tensCounter++;
    	}
    	return retVal;
    }
    
    int getImaginaryNumber(char *input) {
    	char *beg = input;
    	int retVal = 0;
    	while(*beg != '+') {
    		beg++;
    	}
    	beg++;
    	if(*beg == '-') {
    		beg++;
    	}
    	while(*beg >= '0' && *beg <= '9') {
    		beg++;
    	}
    	int tensCounter = 0;
    	while(*beg != '+') {
    		beg--;
    		if(*beg == '+') {
    			break;
    		} else if (*beg == '-') {
    			retVal *= -1;
    		} else {
    			retVal += (*beg-'0') * pow(10, tensCounter);
    		}
    		tensCounter++;
    	}
    	return retVal;
    }
    
    
    char *complexNumberMultiply(char *a, char *b) {
    	int firstWholeNumber = getWholeNumber(a);
    	int secondWholeNumber = getWholeNumber(b);
    	int firstImaginaryNumber = getImaginaryNumber(a);
    	int secondImaginaryNumber = getImaginaryNumber(b);
    
    	int wholeNumber = firstWholeNumber * secondWholeNumber - (firstImaginaryNumber * secondImaginaryNumber);
    	int imaginaryNumber = firstWholeNumber * secondImaginaryNumber + secondWholeNumber * firstImaginaryNumber;
    
    	char *retVal = (char *)malloc(100);
    	sprintf(retVal, "%d+%di", wholeNumber, imaginaryNumber);
    	return retVal;
    }
    

Log in to reply
 

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