You are given a set consisting of non-negative powers of three . Consider the sequence of all non-empty subsets of ordered by the value of the sum of their elements. You are also given a single element . You are required to find the subset at the position in the sequence and print it in increasing order of its elements.
Example:
Input: n=6
Output: 2
3 9
Approach
Java
public class ASubsetSequence {public static void main(String[] args) {StringBuilder sb = new StringBuilder();int count = 0;long powerOf3 = 1;int n = 6;while (n > 0) {if (n % 2 == 1) {sb.append(powerOf3).append(" ");count++;}powerOf3 *= 3;n /= 2;}System.out.println(count);System.out.println(sb.substring(0, sb.length() - 1));}}
No comments:
Post a Comment