Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions F2_2.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
int add(int c1, int n1, int d1, int c2, int n2, int d2, char result[], int len) {
int commonDenominator = d1 * d2;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding a check to ensure that the denominators are not zero before this line would improve robustness.

int numeratorSum = n1 * d2 + n2 * d1;
int characteristicSum = c1 + c2 + numeratorSum / commonDenominator;
numeratorSum %= commonDenominator;

int pos = 0;
int temp = characteristicSum;

if (temp < 0) {
result[pos++] = '-';
temp = -temp;
}

if (temp == 0) {
result[pos++] = '0';
} else {
int divisor = 1;
while (temp / divisor >= 10) {
divisor *= 10;
}
while (divisor > 0) {
result[pos++] = '0' + temp / divisor;
temp %= divisor;
divisor /= 10;
}
}

result[pos++] = '.';
if (numeratorSum == 0) {
result[pos++] = '0';
} else {
int divisor = commonDenominator / 10;
while (divisor > 0 && numeratorSum / divisor == 0) {
result[pos++] = '0';
divisor /= 10;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extracting this logic into a helper function can avoid duplication and improve readability.

while (divisor > 0) {
result[pos++] = '0' + numeratorSum / divisor;
numeratorSum %= divisor;
divisor /= 10;
}
}

result[pos] = '\0';
return 1;
}

int subtract(int c1, int n1, int d1, int c2, int n2, int d2, char result[], int len) {
int commonDenominator = d1 * d2;
int numeratorDiff = n1 * d2 - n2 * d1;
int characteristicDiff = c1 - c2 + numeratorDiff / commonDenominator;
numeratorDiff %= commonDenominator;

int pos = 0;
int temp = characteristicDiff;

if (temp < 0) {
result[pos++] = '-';
temp = -temp;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block can be abstracted into a separate function to handle fractional part conversion and appending.


if (temp == 0) {
result[pos++] = '0';
} else {
int divisor = 1;
while (temp / divisor >= 10) {
divisor *= 10;
}
while (divisor > 0) {
result[pos++] = '0' + temp / divisor;
temp %= divisor;
divisor /= 10;
}
}

result[pos++] = '.';
if (numeratorDiff == 0) {
result[pos++] = '0';
} else {
int divisor = commonDenominator / 10;
while (divisor > 0 && numeratorDiff / divisor == 0) {
result[pos++] = '0';
divisor /= 10;
}
while (divisor > 0) {
result[pos++] = '0' + numeratorDiff / divisor;
numeratorDiff %= divisor;
divisor /= 10;
}
}

result[pos] = '\0';
return 1;
}