The first time one just counts the no of 1's, 2's, 3's and 4's in the room.
The next time they do the same, only to find one deviation from their previous count, which gives them the no of hat they were wearing previously and the one they are wearing right now.
Eg. 1st time the count was 1=4,2=4,3=5,4=2
2nd time the count was 1=3,2=4,3=6,4=2 prev Hat was 3 and the current one is 1
Thus, after each iteration they can come to know the current hat no..