C simple solution,6ms,without extra memory,only in one function


  • 0
    W
    char* addStrings(char* num1, char* num2) {
    	int count = 0,carry = 0,add = 0;
    	char *ret = calloc(1,sizeof(char));
    	memset(ret,0,sizeof(char));
    	int len1 = strlen(num1);
    	int len2 = strlen(num2);
    	if (len1 >= len2) {
    		for (int i = len1 - 1;i >= 0;i--) {
    			ret = realloc(ret, (count + 2) * sizeof(char));
    			memmove(ret + 1, ret, (count + 1) * sizeof(char));
    			if (count<len2) {
    				add = (num1[i] - '0' + num2[len2 - 1 - count] - '0') + carry;
    				carry = add / 10;
    				ret[0] = add - 10 * carry + '0';
    				count++;
    			}
    			else {
    				add = num1[i] - '0' + carry;
    				carry = add / 10;
    				ret[0] = add - 10 * carry + '0';
    				count++;
    			}
    		}
    		if (carry != 0) {
    			ret = realloc(ret, (count + 2) * sizeof(char));
    			memmove(ret + 1, ret, (count + 1) * sizeof(char));
    			ret[0] = carry + '0';
    		}
    		return ret;
    	}
    	else return addStrings(num2, num1);
    }
    

Log in to reply
 

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