Pagini recente » Cod sursa (job #789793) | Cod sursa (job #565756) | Rating Balosu Mihai Costinel (MIhaiBalosu) | Cod sursa (job #1991194) | Cod sursa (job #754723)
Cod sursa(job #754723)
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#define PRECISION 11 // including the end of string
#define END(pointer)\
pointer + (int)(strlen(pointer)-1)*sizeof(char)
#define MIDDLE(pointer)\
pointer + (int)(strlen(pointer)/2)*sizeof(char)
char add (char *out, char operand, char *norm_carry){
if (*out == '\0') *out = 48;
char result = *out - 48 + operand -48+ *norm_carry ;
*out = (result % 10) + 48;
*norm_carry = (result/10);
//printf("result %d operand %d carry %d \n",result, operand, *norm_carry);
return *(out+sizeof(char));
}
void reverse(char *begin, char *end , char *dest_element ){
char temp;
while (begin != dest_element && end !=dest_element){
temp = (*begin) ;//
(*begin) = (*end);
(*end) = temp;
begin += 1;
end -= 1;
}
temp = (*begin) ;//
(*begin) = (*end);
(*end) = temp;
}
int main (){
char *a,*b, *result = NULL,*toadd = NULL, carry = 0;
FILE *in, *out;
int min_size, max_size, i ;
// init
if ((in = fopen ("adunare.in", "r")) == NULL) { printf ("Could not open infile\n"); return -1; }
if (( out = fopen ("adunare.out", "w+"))== NULL){ printf ("Could not open outfile\n"); return -1; }
a = (char *) malloc (sizeof(char) * PRECISION);
b = (char *) malloc (sizeof(char) * PRECISION);
memset(a,48,sizeof(char)*PRECISION);
memset(b,48,sizeof(char)*PRECISION);
//read
fscanf (in,"%s\n",a );
fscanf (in , "%s\n", b);
//reverse
reverse( a, a + (int )( strlen(a) - 1 ) * sizeof(char), a + (int)(strlen(a) / 2)*sizeof(char) );
reverse( b, END(b), MIDDLE(b));
//add
if (strlen (a)> strlen (b)){
min_size = strlen(b);
max_size = strlen (a);
result = a;
toadd = b;
}
else{
min_size = strlen (a);
max_size = strlen (b);
result = b;
toadd = a;
}
//size = (strlen(a)<strlen(b) )? strlen(a) : strlen(b);
for (i = 0 ; i < min_size ; i++){ // basic adding
add(result + i, toadd[i], &carry);
}// case in which carry is non zero
while (carry != 0){
add (result+i,'0',&carry);
i++;
result[i] = '\0';
}
reverse (result , END(result), MIDDLE(result));
fprintf (out, "%s\n", result);//
fclose(in);
fclose(out);
return 0;
}