C language Solution, 6ms


  • 0
    G
    char *reverse(char *s) {
    	char *p_lo = s;
    	char *p_hi = s;
    	while ('\0' != *(p_hi + 1))
    		p_hi++;
    	while (p_lo < p_hi) {
    		char n = *p_lo;
    		*p_lo = *p_hi;
    		*p_hi = n;
            p_lo++;
            p_hi--;
    	}
    	
    	return s;
    }
    
    char charAdd(char x, char y, char carry, char *p_carry) {
    	char n = (x - 48) + (y - 48) + (carry - 48);
    	if (n > 9) {
    		n -= 10;
    		*p_carry = '1';
    	}
    	else
    		*p_carry = '0';
    
    	return (n + 48);
    }
    
    char* addStrings(char* p_num_a, char* p_num_b) {
    	if (NULL == p_num_a)
    		return p_num_b;
    	if (NULL == p_num_b)
    		return p_num_a;
    	char* p_a_end = p_num_a;
    	char* p_b_end = p_num_b;
    	while ('\0' != *(p_a_end + 1))
    		p_a_end++;
    	while ('\0' != *(p_b_end + 1))
    		p_b_end++;
            int max = (p_b_end - p_num_b) > (p_a_end - p_num_a) ? (p_b_end - p_num_b) : (p_a_end - p_num_a);
            char* buffer = (char*)malloc(max * 2);
    	char* p_sum = buffer;
    	char carry = '0';
    	while (p_a_end >= p_num_a || p_b_end >= p_num_b) {
            if (p_a_end < p_num_a && p_b_end >= p_num_b)
                *p_sum = charAdd('0', *p_b_end, carry, &carry);
            else if (p_b_end < p_num_b && p_a_end >= p_num_a)
                *p_sum = charAdd(*p_a_end, '0', carry, &carry);
            else if (p_a_end >= p_num_a && p_b_end >= p_num_b)
                *p_sum = charAdd(*p_a_end, *p_b_end, carry, &carry);
    		p_sum++;
            p_a_end--;
            p_b_end--;
    	}
    	if ('0' != carry) {
    		*p_sum = charAdd('0', '0', carry, &carry);
    		p_sum++;
    	}
    	*p_sum = '\0';
    
    	return reverse(buffer);
    }
    
    

Log in to reply
 

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