Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | C ++ program of the above approach ; Function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; Traverse the array of strings ; Convert the current array element to a string ; Sort each string in descending order ; Convert the string to equivalent integer ; Calculate square root of current array element ; Calculate perfect square ; Find the nearest perfect square ; Sort the array in ascending order ; Print the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { string s = to_string ( arr [ i ] ) ; sort ( s . begin ( ) , s . end ( ) , greater < char > ( ) ) ; arr [ i ] = stoi ( s ) ; int sr = sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) arr [ i ] = a ; else arr [ i ] = b ; } sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 29 , 43 , 28 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , N ) ; return 0 ; }