Last active 1702396352

Serpent03 revised this gist 1702396351. Go to revision

1 file changed, 74 insertions

dpal.c(file created)

@@ -0,0 +1,74 @@
1 + #include <stdio.h>
2 + #include <string.h>
3 + #include <stdlib.h>
4 +
5 + char* rev(char buf[]) {
6 + for (int i = 0; i < strlen(buf); i++) {
7 + char t = buf[i];
8 + buf[i] = buf[strlen(buf) - i - 1];
9 + buf[strlen(buf) - i - 1] = t;
10 + }
11 + return buf;
12 + }
13 +
14 + char* convertToBase(int number, int base, char buf[]) {
15 + int idx = 0;
16 + char c[2];
17 + while (number > 0) {
18 + sprintf(c, "%d", number % base);
19 + // if we were converting the base of anything bigger than
20 + // base10, we would have needed a special function to return
21 + // A - F for hexadecimal formats.
22 + buf[idx++] = c[0];
23 + number /= base;
24 + }
25 + buf[idx] = '\0';
26 + // we'll have to reverse the string before returning it,
27 + // because we're dividing the original number from the "one's" place -- remainder of
28 + // number % base is always the least significant bits
29 + return rev(buf);
30 + }
31 +
32 + int isPalindrome(char* str) {
33 + int ptra = 0;
34 + int ptrb = strlen(str) - 1;
35 + while (ptra <= ptrb) {
36 + if (str[ptra] != str[ptrb]) {
37 + return 0;
38 + }
39 + ptra++;
40 + ptrb--;
41 + }
42 + return 1;
43 + }
44 +
45 + int main() {
46 + int S = 25;
47 + int N = 3;
48 +
49 + int len = N;
50 + int* palindromeNums = (int*)malloc(len * sizeof(int));
51 + int idx = 0;
52 + char buf[100];
53 +
54 + while (N >= 0) {
55 + int cnt = 0;
56 + for (int i = 2; i < 11; i++) {
57 + char* retStr = convertToBase(S, i, buf);
58 + if (isPalindrome(retStr)) {
59 + cnt++;
60 + }
61 + if (cnt > 1) {
62 + palindromeNums[idx++] = S;
63 + break;
64 + }
65 + }
66 + S++;
67 + N--;
68 + }
69 +
70 + for (int i = 0; i < len; i++) {
71 + printf("%d\n", palindromeNums[i]);
72 + }
73 +
74 + }
Newer Older