problem-specifications icon indicating copy to clipboard operation
problem-specifications copied to clipboard

Reversed digits between bases

Open LegalizeAdulthood opened this issue 8 years ago • 3 comments

Print out all the numbers from 1 to 65535 for which the hexadecimal representation is the digit-wise reverse of the decimal representation. What about octal? What about other bases?

What this explores is a little string manipulation and a little formatting of numbers in different bases. Coming from a strong C++ background and having worked at hardware companies, dealing in bases other than 10 is no big deal to me, but lots of newer programmers are coming from a web background where dealing in octal or hexadecimal is not routine. This could stretch their muscles a little bit more than mine.

// brute force solution, but what about solving the integer digit
// equation?
//  16*d1 + d0 = 10*d0 + d1
// For what integral values of d0 and d1 is this true?
// How do you deal with fewer or more than 2 digits with a digit equation?
//
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    for (int i = 1; i < 65535; ++i) {
        ostringstream hx;
        hx << hex << i;
        ostringstream dc;
        dc << i;
        string hxs = hx.str();
        string dcs = dc.str();
        if (hxs.length() != dcs.length()) {
            continue;
        }
        reverse(dcs.begin(), dcs.end());
        if (hxs == dcs) {
            cout << i << '\n';
        }
    }
}

Results:

1
2
3
4
5
6
7
8
9
53
371
5141

LegalizeAdulthood avatar Dec 04 '17 21:12 LegalizeAdulthood

I like this idea. It's playful, and it fits with the "all your base" idea, so that in v2 one of these would likely unlock the other (or both could be unlocked by a third).

kytrinyx avatar Dec 04 '17 22:12 kytrinyx

We now have an exercise to convert between bases: https://github.com/exercism/problem-specifications/blob/main/exercises/all-your-base/description.md Do you still want to pursue this exercise idea @LegalizeAdulthood?

ErikSchierboom avatar Jan 14 '22 11:01 ErikSchierboom

As evidenced by this tardy reply, I'm not really active in exercism anymore :).

If someone else wants to run with it, that's great.

LegalizeAdulthood avatar Apr 22 '22 17:04 LegalizeAdulthood