ONEZERO - Ones and zeros is an easy BFS + Modular Arithmetic problem.
I am assuming that you have already understood the problem statement, otherwise go back and read the problem statement again.
If you are not familiar to the term BFS, i suggest you to first read basics of BFS.
In this problem, we have a made a queue which contains pairs, and each pair consists of a string (as number may exceed the integer limit) and an integer.
Now let us talk about the modular arithmetic concept we are going to use in this problem, let us take an example, we have to find 356 % 8, which is equal to 4. Now let us try to find this in the following way:
3 % 8 = 3
now multiply 3 to 10 and add next digit = 3*10+5 = 35
35 % 8= 3
now multiply 3 to 10 and adding next digit = 3 * 10 + 6= 36
36 % 8 =4
By using this method you can be sure that your answer will not be wrong due to integer overflow.
In this problem we will start from 1 and will check if 1 is divisible by n or not, if not then we add 11 and 10 to the queue, and now we know that the remainder of 11 will be ((1 % n) * 10 + 1) % n and for 10 it will be ((1 % n) * 10 + 0) % n at next step, same thing will happen with 11 and 10, and 110, 111, 101, 100 will be added to the queue and so on....
We will repeat this till we didn't find or answer, we can reduce the execution time of code by using visit array.
I am assuming that you have already understood the problem statement, otherwise go back and read the problem statement again.
If you are not familiar to the term BFS, i suggest you to first read basics of BFS.
In this problem, we have a made a queue which contains pairs, and each pair consists of a string (as number may exceed the integer limit) and an integer.
Now let us talk about the modular arithmetic concept we are going to use in this problem, let us take an example, we have to find 356 % 8, which is equal to 4. Now let us try to find this in the following way:
3 % 8 = 3
now multiply 3 to 10 and add next digit = 3*10+5 = 35
35 % 8= 3
now multiply 3 to 10 and adding next digit = 3 * 10 + 6= 36
36 % 8 =4
By using this method you can be sure that your answer will not be wrong due to integer overflow.
In this problem we will start from 1 and will check if 1 is divisible by n or not, if not then we add 11 and 10 to the queue, and now we know that the remainder of 11 will be ((1 % n) * 10 + 1) % n and for 10 it will be ((1 % n) * 10 + 0) % n at next step, same thing will happen with 11 and 10, and 110, 111, 101, 100 will be added to the queue and so on....
We will repeat this till we didn't find or answer, we can reduce the execution time of code by using visit array.
0 comments:
Post a Comment