Home > database >  Convert Integer number to a Boolean List with 3 elements (Java)
Convert Integer number to a Boolean List with 3 elements (Java)

Time:04-05

I have an integer number withing an interval [0,7]. And I want to convert this number into a Boolean list with 3 elements with Java.

1st element in the list has a value of 4, 2nd element has 2 and 3rd element is 1. Their sum makes 7 if all the elements in the list are "true". "False" has a value of 0.

Here are the all possibilities:

If the number is 7 my boolean list is [true, true, true]

If the number is 6 my boolean list is [true, true, false]

If the number is 5 my boolean list is [true, false, true]

If the number is 4 my boolean list is [true, false, false]

If the number is 3 my boolean list is [false, true, true]

If the number is 2 my boolean list is [false, true, false]

If the number is 1 my boolean list is [false, false, true]

If the number is 0 my boolean list is [false, false, false]

I don't want to code this with 8 else if blocks. I think there must be a smarter solution with combinations of the numbers.

Here is my function declaration: default List<Boolean> convertIntToBooleanList(int i);

Do you have any ideas how can I solve it without hardcoding?

Thanks!

CodePudding user response:

You need to convert your number to base 2, then, for each bit, set the corresponding value in the array to true if the bit is 1.
Example:

7 = 111 = [true, true, true]
5 = 101 = [true, false, true]
4 = 100 = [true, false, false]

Basic Java implementation (not well versed with Java, so the solution might be made more optimal):

public static void main (String[] args) throws java.lang.Exception
    {
        Integer x = 3;
        String binary = String.format("%3s", Integer.toBinaryString(x)).replace(' ', '0');
        List<Boolean> list = new ArrayList<Boolean>();
        for (int i = 0; i < binary.length(); i  ) {
            list.add(binary.charAt(i) == '1');
        }
        System.out.println(list);
    }

CodePudding user response:

You can use number&1 to confirm the first bit is 1 or 0, and use >> to shift each bit to the first.

public static List<Boolean> convertIntToBooleanList(int i) {
    List<Boolean> list = new ArrayList<>();
    list.add((i>>2&1)!=0);
    list.add((i>>1&1)!=0);
    list.add((i&1)!=0);
    return list;
}
  • Related