Sort 92 Discussions, By:
Please Login in order to post a comment
Here is my code as well as an explanation of what I'm doing. there is really no explanation of any of this given in the problem so hopefully this is helpful to some, because it's actually not that bad:
// LINE 1
cout << hex << left << showbase << nouppercase; // formatting
cout << (long long) A << endl; // actual printed part
// LINE 2
cout << dec << right << setw(15) << setfill('_') << showpos << fixed << setprecision(2); // formatting
cout << B << endl; // actual printed part
// LINE 3
cout << scientific << uppercase << noshowpos << setprecision(9); // formatting
cout << C << endl; // actual printed part
So for anyone unfamiliar, C++ has a variety of things called "manipulators" that will change the format of the output printed with "cout". These things are not printed themselves, they just affect the part you are actually printing. A list of these manipulators can be found on this page.
In each of the three outputs, I have put all the relevant manipulators on one line, followed by the actual value which is being printed on the next line.
This problem actually forces two manipulators on you initially which don't seem to be helpful at all. These manipulators are setw and internal. The former sets a fixed width for the output (in this case 15 characters wide) and the latter will align it to the right. We need to basically undo this in the first printed line because we want the hexadecimal printout to be left-aligned instead.
Printed Line 1
The manipulators I used here are hex (which will output the number in hexadecimal format), left (which will align the number to the left), showbase (which will make sure the hexadecimal number has a '0x' at the beginning), and nouppercase (which converts all alphabetic hexadecimal values to lowercase).
Printed Line 2
In this section, I actually have to undo some of the previous manipulations.
Printed Line 3
IMHO this must be the most unsavory question in Hackerrank. They even added additional code prior to yours to make sure that yours will not work properly. Really disappointed by this one...
FYI it's a good idea to cast the hex value as a long if you don't pass test cases 6-9.
My Solution using printf
printf("%.*s%+.2f\n",15 - to_string((int)B).length() - 4,"_______________",B);
It's crucial to convert A to long long instead of int, otherwise a few tests fail.
Here's my full solution:
ios_base::fmtflags flags = cout.flags();
cout << setw(0) << "0x" << hex << nouppercase << left << (long long)A << endl;
cout << fixed << setw(15) << setprecision(2) << setfill('_') << right << showpos << B << endl;
cout << scientific << setw(15) << setprecision(9) << noshowbase << right << C << endl;