Title:
Given a number, let you delete several digits in it to make it a perfect square number, of course, you can not delete it, if you can't delete it anyway, output -1, and find the minimum number of digits that need to be deleted to meet the meaning of the question number.
Ideas:
The general idea is, violent enumeration, I directly convert the given number into a string
scanf("%d", &n);
itoa (n, sn, 10);
The above two-step code is to convert the integer type to a string. The itoa( ) function and the atoi( ) function are inverse to each other. When the conversion is completed, violently enumerate the perfect squares within n, and then convert the enumerated perfect squares into strings. The itoa( ) function is also used, and then the bitwise comparison is performed, and a min is used to maintain it. Set two positions p1, p2, which are the starting positions of integer n and i ^ 2 respectively, <i> Then p1 always executes ++, and sweeps to the end of integer n, <ii> If it encounters the first position with i ^ 2 If a digit is equal, p2++ is executed, scanning the next digit of i^2. Note the order of these two steps.
My AC code:
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int Inf = 1e9 + 7;
int n, ans;
char sn[12], si[12];
int main() {
scanf("%d", &n);
itoa(n, sn, 10);
ans = Inf;
int ln = strlen(sn);
for(int i = 1; i * i <= n; i++) {
itoa(i * i, si, 10);
int li = strlen(si);
int p1 = 0, p2 = 0; //p1对应n数位位置, p2对应 i^2 数位位置
while(p1 < ln) {
if(p1 < ln && p2 < li && sn[p1] == si[p2]) p2++;
p1++;
}
if(p2 == li) ans = min(ans, ln - li);
}
if(ans == Inf) puts("-1");
else printf("%d\n", ans);
}