Esthetic numbers | Rosetta Code | #20

URL to the problem page: http://rosettacode.org/wiki/Esthetic_numbers


An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.

E.G.


  • 12 is an esthetic number. One and two differ by 1.
  • 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
  • 890 is not an esthetic number. Nine and zero differ by 9.


These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.

Esthetic numbers are also sometimes referred to as stepping numbers.


Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.



#include <iostream>
using namespace std;

int finddigits(int a) {
    int result = 1;
    while (a >= 10) {
        result++;
        a /= 10;
    }
    return result;
}

int power(int aint b) {
    int result = 1;
    for (int i = 0; i < b; i++) {
        result *= a;
    }
    return result;
}

int main() {
    int cnt, digitnumber;
    cout << "Esthetic numbers with a magnitude between 1000 and 9999 are:" << endl << endl;
    for (int i = 1000; i < 10000; i++) {
        cnt = 0;
        digitnumber = finddigits(i);
        int* digits = new int[digitnumber];
        for (int j = 0; j < digitnumber; j++) {
            digits[j] = (i % power(10, j + 1)) / power(10, j);
        }
        for (int j = 1; j < digitnumber; j++) {
            if (digits[j] - digits[j - 1] != 1 && digits[j] - digits[j - 1] != -1) {
                cnt++;
                break;
            }
        }
        if (cnt == 0) {
            cout << i << ", ";
        }
    }
    cout << endl;
    return 0;
}



Comments

My photo
Ercan Tomac
instagram.com/ercantomac