Implement IsOdd function in Java

Views:
 
Category: Education
     
 

Presentation Description

Implement IsOdd function in Java

Comments

Presentation Transcript

Implement isOdd function: 

Implement isOdd function By Rohit Ghatol rohitsghatol@gmail.com

Interview Begins: 

Interview Begins Interviewer: Write a function to check if a number is Odd or not

Interview Begins: 

Interview Begins Interviewer: Write a function to check if a number is Odd or not Candidate: That’s simple

Interview Begins: 

Interview Begins Interviewer: Write a function to check if a number is Odd or not Candidate: That’s simple public boolean isOdd(int num){ if(num%2==1){ return true; } else { return false; } }

Interview Begins: 

Interview Begins Interviewer: Ok, what happens when I pass a negative value. Candidate : Ohh!! Yes, let me change it

Interview Begins: 

Interview Begins Interviewer: Ok, what happens when I pass a negative no. Candidate : Ohh!! Yes, let me change it public boolean isOdd(int num){ if(num%2==1 || num%2==-1){ return true; } else { return false; } }

Interview Begins: 

Interview Begins Interviewer: Ok!!...hmm.. Can you make it more efficient Candidate : hmmm…. Can’t say much

Interview Begins: 

Interview Begins Interviewer: What is more efficient than arithmetic operations?

Interview Begins: 

Interview Begins Interviewer: What is more efficient than arithmetic operations? Candidate : On what terms efficient? Interviewer: CPU cycles… Candidate : Can’t say.. Interviewer : How about bitwise operations? Candidate : Ok so the hint is use bitwise operator!!

Interview Begins: 

Interview Begins Interviewer: Yes, Can you try? Candidate: let me see.. public boolean isOdd(int num){ if(num&1==1) return true; } else { return false; } }

Interview Begins: 

Interview Begins Interviewer: Explain Candidate: In binary, the rule for odd number is, last bit is always 1. I applied same rule here and used and operator. num&1 will only be 1 (0001) when the last bit of num is 1 (not 0) indicating it is odd Interviewer: Super, you nailed it!!