Beautiful Year

Beautiful Year
Codeforces easy

Given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.

You can assume that year is at least 1000 and at most 9000.

For example, for year 1987, the next such year is 2013.

Solution

We can start increasing the year by one, until we get a year whose all digits are different.

#include<iostream>
using namespace std;

int main () {
    int year;
    cin >> year;

    year += 1;
    while (allDifferentDigits(year) == false) {
        year += 1;
    }

    cout << year << '\n';
}

Now, how do we check whether number has all different digits? Well, notice that our number has exactly four digits. This means that we can take the last digit as remainder of division by 10. Then, we can subtract it, divide by 10 and continue this process three more times. We then get four digits and we check if they are equal.

bool allDifferentDigits(int year) {
    int digit1 = year % 10;
    year = (year - digit1) / 10;

    int digit2 = year % 10;
    year = (year - digit2) / 10;


    int digit3 = year % 10;
    year = (year - digit3) / 10;

    int digit4 = year % 10;

    if (digit1 != digit2 && digit1 != digit3 && digit1 != digit4
    && digit2 != digit3 && digit3 != digit4) {
        return true;
    } else {
        return false;
    }
}