Self-describing numbers | Rosetta Code | #14
URL to the problem page: http://rosettacode.org/wiki/Self-describing_numbers
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
Display the first 5 Self-describing numbers.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, 2020 is a four-digit self describing number:
- position 0 has value 2 and there are two 0s in the number;
- position 1 has value 0 and there are no 1s in the number;
- position 2 has value 2 and there are two 2s;
- position 3 has value 0 and there are zero 3s.
Display the first 5 Self-describing numbers.
#include <iostream>
using namespace std;
int power(int a, int b) {
int result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
int main() {
int cnt, cnt2, digits, tmp, selfdesnum = 0;
cout << "First 5 Self-describing numbers are:" << endl;
for (int i = 1; selfdesnum < 5; i++) {
digits = 1;
tmp = i;
cnt2 = 0;
while (tmp >= 10) {
digits++;
tmp /= 10;
}
int* numbers = new int[digits];
for (int j = 0; j < digits; j++) {
numbers[j] = (i % power(10, j + 1)) / power(10, j);
}
for (int j = 0; j < digits; j++) {
cnt = 0;
tmp = digits - j - 1;
for (int k = 0; k < digits; k++) {
if (numbers[k] == tmp) {
cnt++;
}
}
if (cnt != numbers[j]) {
cnt2++;
break;
}
}
if (cnt2 == 0) {
selfdesnum++;
cout << i << endl;
}
}
return 0;
}
Comments
Post a Comment