Skip to content

Instantly share code, notes, and snippets.

@HelixSpiral
Last active December 12, 2015 07:29
Show Gist options
  • Save HelixSpiral/4737091 to your computer and use it in GitHub Desktop.
Save HelixSpiral/4737091 to your computer and use it in GitHub Desktop.
Challenge: Take input from a user and print the lowest number possible using the digits from the given input.
#include <iostream> // Needed for std::cout/cin
#include <vector> // Needed for std::vector
#include <string> // Needed for std::string
#include <algorithm> // Needed for std::sort
int main()
{
std::string user_input;
std::vector<int> digits;
bool negative;
std::cout << "Enter an Integer: ";
std::cin >> user_input;
negative = (user_input[0] == '-') ? true : false;
/* We cast to an int before sorting so it sorts the decimal equivilent
then we throw it back to a char before we print. */
for (std::string::iterator x = user_input.begin(); x != user_input.end(); ++x)
/* This will stop all the non-number characters from printing. */
if (static_cast<int>(*x) >= 48 && static_cast<int>(*x) <= 57)
digits.push_back(static_cast<int>(*x));
if (negative)
{
/* We have to do a reverse sort for negatives. */
std::sort(digits.rbegin(), digits.rend());
/* Since we don't print anything but numbers later
we have to print this ahead of time. */
std::cout << "-";
}
else
{
std::sort(digits.begin(), digits.end));
}
for (std::vector<int>::iterator x = digits.begin(); x < digits.end(); ++x)
std::cout << static_cast<char>(*x);
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment