problem-specifications
problem-specifications copied to clipboard
Reversed digits between bases
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