GeeksforGeeks » Interview Questions
Divisible by 3. If yes find the quotient
(7 posts)-
You are given with Binary Representation of a Number.
Using only BitWise operation (No *, / , %) Find if the Number is divisible by 3.
If yes, then return the quotient. else return -1. -
start from 0th bit and count the number of 1s alternatively i.e. 0th bit, 2ndbit, 4th bit....
now start from 1st bit and count the number of 1s alternatively i.e. 1st bit, 3rdbit, 5th bit....
if these two counts are equal,then num is div by 3 -
A good one..
-
@aks:
whats logic behind this?? -
@aks:
whats logic behind this?? -
@ aks and all above
wrong solution
counter Ex 21
binary reprsenetation 00010101
number of set even bits =3
number of set odd bits =0
both the counts are not equal but 21 is divisible by 3correct solution
if(number of set bits at even position - number of set bits at odd position) is divisible by 3
then the number is divisible by 3. -
@All:
Guys thanks for the solution to find whether the number is divisible by 3 or not. (I knew this solution already :P )My question is: If the number is divisible by 3 then what is quotient.
ex 21 / 3 =7.
now as 21 is divisible by 3 then the output should be 7. otherwise the output should be Indivisible or -1. -
Use DFA concept.
state=0;
while(bits are remaining)//move from MSB to LSB { if(bit==0) { if(state==0) state=0; else if(state==1) state=2; else if(state==2) state=1; } else if(bit==1) { if(state==0) state=1; else if(state==1) state=0; else if(state==2) state=2; } } if(state==0) Number is divisible by 3; else Not divisible by 3;
Reply
You must log in to post.