Converting vectors into a 4 digit number

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace 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;
    
} 
closed account (E0p9LyTq)
One quick and dirty method is to build up a string from the individual digits stored in the vector, and then convert the string to an integer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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';
}

8210
8210
Topic archived. No new replies allowed.