-3

I was in a job interview and got this question: " Write a function that gets 2 strings s,t that represents 2 hours ( in format HH: MM: SS ). It's known that s is earlier than t.

The function needs to calculate how many hours between the two given hours contains at most 2 digits.

For example- s- 10:59:00, t- 11:00:59 - Answer- 11:00:00, 11:00:01,11:00:10, 11:00:11.

I tried to do while loops and got really stuck. Unfortunately, I didn't pass the interview.

How can I go over all the hours (every second is a new time) between 2 given hours in java as explained above? Thanks a lot

N.Bar
  • 135
  • 1
  • 1
  • 10

1 Answers1

4

Java 8 allows you to use LocalTime.

LocalTime time1 = LocalTime.parse(t1);
LocalTime time2 = LocalTime.parse(t2);

The logic would require you to count the amount of different digits in a LocalTime, something like

boolean isWinner(LocalTime current) {
    String onlyDigits = DateTimeFormatter.ofPattern("HHmmss").format(current);
    Set<Character> set = new HashSet<>();
    for (int index = 0; index < onlyDigits.length(); index++) {
        set.add(onlyDigits.charAt(index));
    }
    return set.size() <= 2;
}

You can loop between the times like this

int count = 0;
for (LocalTime current = time1; current.isBefore(time2); current = current.plusSeconds(1)) {
    if (isWinner(current)) {
        count++;
    }
}

That's it.

The question is really more geared towards getting a feel of how you'd approach the problem, and if you know about LocalTime API etc.

daniu
  • 14,137
  • 4
  • 32
  • 53