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,
is represented as in binary and it contains four set bits (1-bits). You are also given a number and your task is to determine the number that is less than or equal to and contains the maximum number of set bits in its binary representation.
In other words, print a number that is less than or equal to such that the number of set bits in the binary representation of must
Example:
Input: num=345
Output: 255
Approach
Java
package com.java;public class SetNumbers {public static void main(String[] args) {int num = 345;int value = 0, j = 0;int sum = 0;while (true) {if (sum > num) {sum -= value;break;}value = (int) Math.pow(2, j);sum += value;j++;}System.out.println(sum);}}
No comments:
Post a Comment