Double-base palindromes | Project Euler | Problem #36

URL to the problem page: https://projecteuler.net/problem=36


The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)



#include <iostream>
using namespace std;

int usal(int aint b) {
    int result = 1;
    for (int i = 0; i < b; i++) {
        result *= a;
    }
    return result;
}

int finddigits(int a) {
    int cnt = 1;
    while (a >= 10) {
        a /= 10;
        cnt++;
    }
    return cnt;
}

int main() {
    int i, j, a, b, cnt, cnt2, cnt3, tmp, digitnumber, result = 0;

    for (i = 0; i < 1000000; i++) {
        digitnumber = finddigits(i);
        cnt = 0;
        cnt2 = 0;
        cnt3 = 0;
        int* digits = new int[digitnumber];
        for (j = digitnumber; j > 0; j--) {
            digits[j - 1] = (i % usal(10, j)) / (usal(10, (j - 1)));
        }
        for (a = 0, b = (digitnumber - 1); a < digitnumber, b >= 0; a++, b--) {
            if (digits[a] != digits[b]) {
                cnt2++;
                break;
            }
        }
        if (cnt2 != 0) {
            continue;
        }
        tmp = i;
        while (tmp >= 1) {
            cnt++;
            tmp /= 2;
        }
        tmp = i;
        int* binary = new int[cnt];
        for (j = (cnt - 1); j >= 0; j--) {
            binary[j] = tmp % 2;
            tmp /= 2;
        }
        for (a = 0, b = (cnt - 1); a < cnt, b >= 0; a++, b--) {
            if (binary[a] != binary[b]) {
                cnt3++;
                break;
            }
        }
        if (cnt3 != 0) {
            continue;
        }
        result += i;
    }
    cout << endl << "Sum of all numbers, which are palindromic in base 10 and base 2 less than 1.000.000 is  =  " << result << endl;
    return 0;
}



Comments

My photo
Ercan Tomac
instagram.com/ercantomac