Last active
February 16, 2022 15:11
-
-
Save ZaidaZadkiel/0b5b6e2f2a6f105c82e79ed497fcc390 to your computer and use it in GitHub Desktop.
Numeric Palindrome test to show off
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//compile in linux with: gcc is_palindrome.c -g -lm -lc && ./a.out | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
char* itoa(int value, char* result, int base); | |
int is_palindrome(unsigned int number, int base){ | |
int digits = floor( log(number)/log(base) ); | |
char text[digits+1]; | |
printf( | |
"testing %s in base %d\n", | |
itoa(number, &text[0], base), | |
base | |
); | |
int halfway = digits>>1; | |
for(int i = 0; i != halfway; i++){ | |
int first = (int)floor(number / pow(base, digits-i)) % base; | |
int last = (int)floor(number / pow(base, i)) % base ; | |
printf( | |
"is digit %c same as %c? %s \n", | |
text[digits-i], text[i], | |
first == last | |
? "yes" | |
: "no" | |
); | |
if(first != last ) return 0; | |
} | |
printf("\n"); | |
return 1; | |
} | |
int main (void) | |
{ | |
unsigned int number = 12852184; | |
int base = 12; | |
printf( | |
"Is the decimal number %d a palindrome in base %d? %s\n\n", | |
number, base, | |
is_palindrome(number, base) | |
? "YES" | |
: "NO" | |
); | |
} | |
/** | |
* C++ version 0.4 char* style "itoa": | |
* Written by Lukás Chmela | |
* Released under GPLv3. | |
*/ | |
char* itoa(int value, char* result, int base) { | |
// check that the base if valid | |
if (base < 2 || base > 36) { *result = '\0'; return result; } | |
char* ptr = result, *ptr1 = result, tmp_char; | |
int tmp_value; | |
do { | |
tmp_value = value; | |
value /= base; | |
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; | |
} while ( value ); | |
// Apply negative sign | |
if (tmp_value < 0) *ptr++ = '-'; | |
*ptr-- = '\0'; | |
while(ptr1 < ptr) { | |
tmp_char = *ptr; | |
*ptr--= *ptr1; | |
*ptr1++ = tmp_char; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment