// Q: Find minimum and maximum number made out of all 9 digits which is a perfect square
bool isPerfectSquare(const char *s) {
int num;
{
stringstream ss(s);
if( !(ss >> num) ) return false;
static const bool possible_sq[] = {true, true, false, false, true, true, true, false, false, true};
if( !possible_sq[num % 10] ) return false;
}
const int c = num;
int res = 0;
int bit = 1 << 30;
while (bit > num) bit >>= 2;
while (bit != 0) {
if (num >= res + bit) {
num -= res + bit;
res = (res >> 1) + bit;
} else res >>= 1;
bit >>= 2;
}
return (res * res == c);
}
int main() {
char num[] = "123456789";
char *const f = &num[0];
char *const t = &num[9];
bool found = false;
do {
if( isPerfectSquare(num) ) {
cout << "Smallest is: " << num << endl;
found = true;
break;
}
} while( next_permutation(f, t) );
if( !found ) {
cout << "None found" << endl;
return 0;
}
sort( f, t, std::greater<char>() );
do {
if( isPerfectSquare(num) ) {
cout << "Largest is: " << num << endl;
break;
}
} while( next_permutation( f, t, std::greater<char>() ) );
}