Submission
Status:
---------
Score: 0
User: Jokul
Problemset: บวกเลขฐาน
Language: c
Time: 0.002 second
Submitted On: 2025-03-01 09:33:29
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 50
// Function to add two numbers in a given base
void addNumbersInBase(const char *num1, const char *num2, int base, char *result) {
int len1 = strlen(num1);
int len2 = strlen(num2);
int maxLength = (len1 > len2 ? len1 : len2) + 1; // +1 for possible carry
int carry = 0;
int i, j, k = 0;
// Reverse the strings to make addition easier
char revNum1[MAX_LENGTH], revNum2[MAX_LENGTH];
for (i = 0; i < len1; i++) {
revNum1[i] = num1[len1 - 1 - i];
}
revNum1[len1] = '\0';
for (i = 0; i < len2; i++) {
revNum2[i] = num2[len2 - 1 - i];
}
revNum2[len2] = '\0';
// Perform addition
for (i = 0; i < maxLength; i++) {
int digit1 = (i < len1) ? (isdigit(revNum1[i]) ? revNum1[i] - '0' : toupper(revNum1[i]) - 'A' + 10) : 0;
int digit2 = (i < len2) ? (isdigit(revNum2[i]) ? revNum2[i] - '0' : toupper(revNum2[i]) - 'A' + 10) : 0;
int sum = digit1 + digit2 + carry;
carry = sum / base; // Calculate carry for next position
sum = sum % base; // Get the digit to store in the result
// Store the result digit
if (sum < 10) {
result[k++] = sum + '0';
} else {
result[k++] = (sum - 10) + 'A';
}
}
// If there's a carry left, add it to the result
if (carry > 0) {
result[k++] = carry + '0';
}
// Null-terminate the result string
result[k] = '\0';
// Reverse the result to get the correct order
for (i = 0; i < k / 2; i++) {
char temp = result[i];
result[i] = result[k - 1 - i];
result[k - 1 - i] = temp;
}
}
int main() {
int base;
char num1[MAX_LENGTH], num2[MAX_LENGTH], result[MAX_LENGTH];
// Input base
printf("Base: ");
scanf("%d", &base);
// Input two numbers
printf("Num1: ");
scanf("%s", num1);
printf("Num2: ");
scanf("%s", num2);
// Add the numbers in the specified base
addNumbersInBase(num1, num2, base, result);
// Output the result
printf("OUTPUT %s\n", result);
return 0;
}