A subset in a sequence

You are given a set S consisting of non-negative powers of three S={1, 3, 9, 27, ...}. Consider the sequence of all non-empty subsets of S ordered by the value of the sum of their elements. You are also given a single element n. You are required to find the subset at the nth 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(0sb.length() - 1));
    }
}


No comments:

Post a Comment