Algorithm
You are given an integer n from 1 to 1018 without leading zeroes.
In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.
What is the minimum number of moves you have to make to obtain a number that is divisible by 25? Print -1 if it is impossible to obtain a number that is divisible by 25.
The first line contains an integer n (1≤n≤1018). It is guaranteed that the first (left) digit of the number n is not a zero.
If it is impossible to obtain a number that is divisible by 25, print -1. Otherwise print the minimum number of moves required to obtain such number.
Note that you can swap only adjacent digits in the given number.
5071
4
705
1
1241367
-1
In the first example one of the possible sequences of moves is 5071 → 5701 → 7501 → 7510 → 7150.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int m;
long long n;
vector<int> all, tmp;
int main() {
scanf("%lld", &n);
while(n != 0) {
all.push_back(n % 10);
n /= 10;
}
reverse(all.begin(), all.end());
m = all.size();
int res = 1000;
for(int i = 0; i < all.size(); ++i) {
for(int j = 0; j < all.size(); ++j) {
if(i == j)
continue;
if(all[i] == 0 && all[j] == 0) {
res = min(res, m - i + m - j - 3);
} else if(all[i] == 2 && all[j] == 5 ||
all[i] == 5 && all[j] == 0 ||
all[i] == 7 && all[j] == 5) {
int tmp = m - i + m - j - 2 - (i < j), idx = -1;
for(int k = 0; k < all.size(); ++k)
if(all[k] == 0) {
idx = k;
break;
}
if(idx != j && idx != -1 && ((i == 0 && idx == 1) || (i == 0 && j == 1 && idx == 2) || (j == 0 && idx == 1))) {
for(int k = idx + 1; k < all.size(); ++k)
if(all[k] != 0) {
idx = k;
break;
}
if(all[idx] == 0)
tmp = 1e9;
else
tmp += idx - (j == 1 ? 2 : 1);
}
res = min(res, tmp);
}
}
}
if(res == 1000)
puts("-1");
else
printf("%d\n", res);
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
Demonstration
Codeforces Solution-E. Divisibility by 25-Solution in C, C++, Java, Python