Easy Explanation:)
So our question says the binary watch has 4 LEDs in which the hour is from(0-11) and we can't write 07,08,01 as an hour. So, Our first loop starts from 0 to 11. The minute is from (00 to 59) i.e we can represent the minute in 05,09 and so on. So, Our second loop starts from 0 or 00 to 59.
Our question says to return the ArrayList those contain turnedOn number of LEDs are on. Let us understand through an example:- let turnedOn=2 i.e. we have to return ArrayList those contains time format like 2 LEDs are on e.g 16.00,0.16,8.01 etc.Now our task is we have to contain all this type of time formats in a single ArrayList and return it. (Observe one thing that both side number of ":" are in the form of 2^n except '0')So for that, we use builtin functions Integer.bit count() and String.format().
bitcount() count the bits in a number of binary format.Let a number is 4 i.e 0100 , Total number of 1 bit present is 1 i.e. Integer.bitCount(4) will return 1 and another number is 8 i.e 1000, Total number of 1 bit present is 1 i.e. Integer.bitCount(8) will return 1.
Now, Integer.bitCount(4)+Integer.bitCount(8)=2=turnedOn
Now our task is when the condition is satisfied we have to return the time format like 4:08, So here before 8 we have to add a "0" to form "08".
So we will use ,String.format(%02d,8) so it will return a formatted string as "08" i.e this function says I can add '0' with your number until the length is greater than 2.
Let for first loop i=4 and second loop j=8 i.e time format will be 4:08.Here turnedOn=2 . Now Integer.bitCount(4)+Integer.bitcount(8)==2==turnedOn
so add 4:08 into list and similarly add all strings formed and return the list. */ class Solution { public List readBinaryWatch(int turnedOn) { List times=new ArrayList<>(); for(int i=0;i<=11;i++){ for(int j=0;j<=59;j++){ if(Integer.bitCount(i)+Integer.bitCount(j)==turnedOn){ times.add(String.format("%d:%02d",i,j)); } } } return times; } }