Advertisement
GokulDeep

SubsetBit

Feb 27th, 2024 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. package com.gokul.demo.Success;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class SubsetBit {
  7.     public static void main(String[] args) {
  8.  
  9.         SubsetBit sub = new SubsetBit();
  10.         int[] arr = new int[] { 1, 2, 3, 4 };
  11.         sub.subsets(arr);
  12.     }
  13.  
  14.     List<List<Integer>> opList = new ArrayList<>();
  15.  
  16.     public List<List<Integer>> subsets(int[] nums) {
  17.         for (int i = 0; i < Math.pow(2, nums.length); i++) {
  18.  
  19.             opList.add(getBinary(i, nums.length, nums));
  20.  
  21.         }
  22.         return opList;
  23.     }
  24.  
  25.     private List<Integer> getBinary(int num, int size, int[] nums) {
  26.         List<Integer> minList = new ArrayList<>();
  27.         String binaryString = Integer.toBinaryString(num);
  28.  
  29.         while (binaryString.length() < size) {
  30.             binaryString = "0" + binaryString;
  31.         }
  32.         char[] charArray = binaryString.toCharArray();
  33.         for (int i = 0; i < charArray.length; i++) {
  34.             if ('1' == charArray[i]) {
  35.                 minList.add(nums[i]);
  36.             }
  37.         }
  38.         return minList;
  39.     }
  40.  
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement