-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMath_KaprekarsConstant
101 lines (84 loc) · 2.31 KB
/
Math_KaprekarsConstant
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*Challenge
Have the function KaprekarsConstant(num) take the num parameter being passed which will be
a 4-digit number with at least two distinct digits.
Your program should perform the following routine on the number:
Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number),
and subtract the smaller number from the bigger number.
Then repeat the previous step. Performing this routine will always cause you to reach
a fixed number: 6174. Then performing the routine on 6174 will always give
you 6174 (7641 - 1467 = 6174). Your program should return the number of times this
routine must be performed until 6174 is reached.
For example: if num is 3524 your program should return 3 because of the following steps:
(1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174.
Hard challenges are worth 15 points and you are not timed for them.
Sample Test Cases
Input:2111
Output:5
Input:9831
Output:7*/
#include <iostream>
#include <string>
using namespace std;
void sort(string& str, bool ascending) {
bool change = true;
/*Bubble sort*/
while (change) {
change = false;
for (int i = 0; i < str.length() - 1; i++) {
if (ascending && str[i] > str[i + 1]) {
change = true;
char temp = str[i];
str[i] = str[i + 1];
str[i + 1] = temp;
}
else if (!ascending && str[i] < str[i+1]) {
char temp = str[i];
str[i] = str[i + 1];
str[i + 1] = temp;
change = true;
}
}
}
}
int KaprekarsConstant(int num) {
int counter = 0;
string min, max;
bool t = true;
while (num != 6174) {
min = to_string(num);
max = to_string(num);
sort(min, true);
sort(max, false);
num = atoi(max.c_str()) - atoi(min.c_str());
if (num < 10) {
string n = to_string(num) + "000";
num = atoi(n.c_str());
}
else if (num < 100) {
string n = to_string(num) + "00";
num = atoi(n.c_str());
}
else if (num < 1000) {
string n = to_string(num) + "0";
num = atoi(n.c_str());
}
counter++;
}
return counter;
}
bool check(int num) {
string n = to_string(num);
for (int i = 0; i < 3; i++)
if (n[i] != n[i + 1])
return true;
return false;
}
void main() {
int num;
cin >> num;
if (!check(num))
cout << "Numbers must have at least 2 distinct digits!";
else
cout << KaprekarsConstant(num);
system("pause>0");
}