Submission
Status:
PPPPPPPPP
Subtask/Task Score:
100/100
Score: 100
User: lingusso
Problemset: บวกเลขฐาน
Language: c
Time: 0.002 second
Submitted On: 2025-10-12 13:57:53
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For toupper or similar if needed, though not strictly required here
// Function to convert a base-B number string to its decimal (base-10) value
long long base_to_decimal(const char* num_str, int base) {
long long decimal_value = 0;
int len = strlen(num_str);
for (int i = 0; i < len; i++) {
int digit_value;
char c = num_str[i];
if (c >= '0' && c <= '9') {
digit_value = c - '0';
} else if (c >= 'A' && c <= 'Z') {
// For digits > 9, like 'A'=10, 'B'=11, etc.
digit_value = c - 'A' + 10;
} else if (c >= 'a' && c <= 'z') {
// Optional: Handle lowercase letters if needed
digit_value = c - 'a' + 10;
} else {
// Invalid character
continue;
}
// Check if the digit is valid for the given base
if (digit_value >= base) {
fprintf(stderr, "Error: Digit %c is invalid for base %d.\n", c, base);
return -1; // Return error value
}
// Conversion core logic: decimal = decimal * base + digit_value
decimal_value = decimal_value * base + digit_value;
}
return decimal_value;
}
// Function to convert a decimal number to a base-B string and print it
void decimal_to_base(long long sum, int base) {
if (sum == 0) {
printf("0\n");
return;
}
// Using an int array to store digit values (0-B-1)
int output_digits[40];
int r = 0;
while (sum > 0) {
int remainder = sum % base;
output_digits[r] = remainder;
sum /= base;
r++;
}
// Print the digits in REVERSE order (from most significant to least significant)
for (int i = r - 1; i >= 0; i--) {
int digit_value = output_digits[i];
if (digit_value > 9) {
// Convert 10 -> 'A', 11 -> 'B', etc.
// ASCII of 'A' is 65. 'A' - 10 = 55. This is equivalent to your original 'digit_value + 55'
printf("%c", digit_value + 'A' - 10);
} else {
// Convert 0 -> '0', 1 -> '1', etc.
// ASCII of '0' is 48. This is equivalent to your original 'digit_value + 48'
printf("%c", digit_value + '0');
}
}
printf("\n"); // Add a newline at the end
}
int main() {
int n; // n is the base B
if (scanf("%d", &n) != 1) {
return 1; // Handle read error
}
// Check for valid base (e.g., base 2 to 36)
if (n < 2 || n > 36) {
fprintf(stderr, "Error: Base must be between 2 and 36.\n");
return 1;
}
char num1[40], num2[40];
if (scanf("%39s", num1) != 1 || scanf("%39s", num2) != 1) {
return 1; // Handle read error
}
// Convert both numbers to decimal
long long decinum1 = base_to_decimal(num1, n);
long long decinum2 = base_to_decimal(num2, n);
// Check if conversion failed
if (decinum1 == -1 || decinum2 == -1) {
return 1;
}
// Add the numbers in decimal
long long sum = decinum1 + decinum2;
// Convert the sum back to base n and print
decimal_to_base(sum, n);
return 0;
}