Here is a C++ program where you are given an array of numbers. Append each element one after another in a way that the resulting number is the largest possible number you can make out of all the given array elements.
Output: 969660548546
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<string> | |
#include <bits/stdc++.h> | |
using namespace std; | |
void printArray(int arr[], int n); | |
void rearrangeArray(int arr[], int n); | |
long append(int arr[], int n); | |
bool firstDigitLarger(int a, int b); | |
bool firstDigitLarger(int a, int b) { | |
int aFirst, bFirst, digit1, digit2; | |
while(a != 0) { | |
digit1 = a; | |
a /= 10; | |
} | |
aFirst = digit1; | |
while(b != 0) { | |
digit2 = b; | |
b /= 10; | |
} | |
bFirst = digit2; | |
return aFirst > bFirst; | |
} | |
long append(int arr[], int n) { | |
string appended; | |
for(int i = 0; i<n; i++) { | |
std::string base = std::to_string(arr[i]); | |
appended += base; | |
} | |
return std::stol(appended); | |
} | |
void rearrangeArray(int arr[], int n) { | |
sort(arr, arr+n, greater<int>()); | |
sort(arr, arr+n, firstDigitLarger); | |
} | |
void printArray(int arr[], int n) { | |
for(int i = 0; i< n; i++) { | |
cout<<arr[i]<<" "; | |
} | |
} | |
int main() { | |
int arr[] = {546,548,60,9,696}; | |
int n = sizeof(arr)/sizeof(arr[0]); | |
rearrangeArray(arr,n); | |
cout<<append(arr,n); | |
return 0; | |
} |
No comments:
Post a Comment