USACO 1.2 Palindromic Squares (进制转换)

#include <stdio.h>
#define DEBUG 0
#define TESTCASES 9

#define SIZE_CHARS 17

char *digits = "0123456789ABCDEFGHIJK";
int base;

void transform(int decimalNum, char numStr[], int *len){
	int quotient = 0;
	int numOfChars = 0;
	while ( (quotient = decimalNum / base) != 0){
		numStr[numOfChars++] = digits[decimalNum % base];
		decimalNum = quotient;
	}
	numStr[numOfChars++] = digits[decimalNum % base];
	numStr[numOfChars] = '\0'; 
	*len = numOfChars;

	int halfNumOfChars = numOfChars / 2;
	int indexOfChar;
	for (indexOfChar = 0; indexOfChar < halfNumOfChars; indexOfChar++){
		char temp = numStr[indexOfChar];
		numStr[indexOfChar] = numStr[numOfChars - 1 - indexOfChar];
		numStr[numOfChars - 1 - indexOfChar] = temp;
	}	
}

int isPalindromic(char numStr[], int len){
	int half = len / 2;
	int indexOfChar;
	for (indexOfChar = 0; indexOfChar < half; indexOfChar++){
		if (numStr[indexOfChar] != numStr[len - 1 - indexOfChar])
			return 0;
	}
	return 1;
}

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "inputX.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("#%d\n", testCase);
#endif

	scanf("%d", &base);
	int num;
	for (num = 1; num <= 300; num++){
		int square = num * num;
		char squareStr[SIZE_CHARS];
		int len;
		transform(square, squareStr, &len);
		if (isPalindromic(squareStr, len) == 1){
			char numStr[SIZE_CHARS];
			transform(num, numStr, &len);
			printf("%s %s\n", numStr, squareStr);
		}
	}

#if DEBUG
	}
#endif
	return 0;
	
}

你可能感兴趣的:(进制转换,USACO,1.2,Palindromic,Squares)