Hello. I was recently doing a coding challenge where one step includes rearranging the digits from a 4 digit number to make it the largest it could be, using a vector. However, now I don't know how to store the separate digits into an integer.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
usingnamespace std;
bool sortDigits(int num1, int num2)
{
return num1 > num2;
}
int KaprekarsConstant(int num) {
vector<int> distinctNumberCheck;
int largerNumber;
int smallerNumber;
int count;
int numberSizeCount = 0;
int numberReplacement = num;
// Very the length of the number
while (numberReplacement)
{
numberReplacement /= 10;
numberSizeCount++;
}
if (numberSizeCount == 4)
{
int distinctDigitChecker = 0;
numberReplacement = num;
// Add the numbers to the vector
for (int i = 0; i < numberSizeCount; i++)
{
distinctNumberCheck.push_back(numberReplacement % 10);
numberReplacement /= 10;
}
// Verify if there at least 2 distinct digits in the number
for (int i = 0; i < numberSizeCount - 1; i++)
{
if (distinctNumberCheck[i] == distinctNumberCheck[i + 1])
{
distinctDigitChecker++;
}
}
// Sorting the numbers...
if (distinctDigitChecker < 3)
{
// Smaller number
sort(distinctNumberCheck.begin(), distinctNumberCheck.end()); // I would like to store this in an integer
// Larger number
sort(distinctNumberCheck.begin(), distinctNumberCheck.end(), sortDigits);
}
}
return num;
}
int main() {
cout << KaprekarsConstant(gets(stdin));
return 0;
}
#include <iostream>
#include <string>
#include <vector>
int main()
{
// you have your ordered int vector, so let's stringize it.
std::vector<int> vec = { 8, 2, 1, 0 };
std::string num_str;
for (size_t itr = 0; itr < vec.size(); itr++)
{
num_str += std::to_string(vec[itr]);
}
std::cout << num_str << '\n';
// we have the completed string, so let's integerize it.
int num = std::stoi(num_str);
std::cout << num << '\n';
}