Monk A loves to complete all his tasks just before the deadlines for introducing unwanted thrill in his life. But, there is another Monk D who hates this habit of Monk A and thinks it's risky.
To test Monk A, Monk D provided him tasks for N days in the form of an array Array, where the elements of the array represent the number of tasks.
The number of tasks performed by Monk A on an ith day is the number of ones in the binary representation of Arrayi.
Monk A is fed up with Monk D, so to irritate him even more, he decides to print the tasks provided in non-decreasing order of the tasks performed by him each day. Help him out!
Example:
Input: n = 4, a = [3,4,7,10]
Output: 4 3 10 7
Approach
C++
#include <bits/stdc++.h>using namespace std;bool cmp(pair<long long,pair<long long, long long>> a, pair<long long,pair<long long, long long>> b){if (a.first == b.first)return a.second.first < b.second.first;return a.first < b.first;}long long count(long long n){long long res = 0;while (n){n = n & (n - 1);res++;}return res;}int main(){long long n = 4;long long a[n] = {3, 4, 7, 10};vector<pair<long long, pair<long long, long long>>> v;for (long long i = 0; i < n; i++){long long cnt = count(a[i]);v.push_back(make_pair(cnt, make_pair(i, a[i])));}sort(v.begin(), v.end(), cmp);for (long long i = 0; i < n; i++)cout << v[i].second.second << " ";cout << "\n";return 0;}
Read Interview Questions
Exception Handling Interview Questions
DBMS Interview Questions Set -1
DBMS Interview Questions Set -2
JPA Interview Questions Set -1
Spring Boot Interview Questions Set 1
Spring Boot Interview Questions Set 2
No comments:
Post a Comment