You are given the binary representation of a number. You must consider the highest number of set bits in the binary representation to complete your task. For example, 23 is represented as (10111) in binary and it contains four-set bits (1-bits). You are also given a number N and your task is to determine the number that is less than or equal to N and contains the maximum number of set bits in its binary representation.
In other words, print a number K that is less than or equal to N such that the number of set bits in the binary representation of K must be maximum
Example:
Input: n = 345
Output: 255
Approach
C++
#include <bits/stdc++.h>using namespace std;int setNumbers(int n){int n1 = n;vector<int> v;while (n > 0){v.push_back(n % 2);n = n / 2;}int f = 0;for (int i = 0; i < v.size(); i++){if (v[i] == 0){f = 1;break;}}if (f == 0)return n1;else{int ans = 0;while (n1 > 0){n1 = n1 / 2;ans = ans * 2 + 1;}return (ans - 1) / 2;}}int main(){int n = 345;cout << setNumbers(n) << "\n";return 0;}
No comments:
Post a Comment