# Implement IsOdd function in Java

Information about Implement IsOdd function in Java

Published on November 30, 2007

Author: rohitsghatol

Source: authorstream.com

Implement isOdd function:  Implement isOdd function By Rohit Ghatol [email protected] 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!!

30. 11. 2007
0 views

30. 11. 2007
0 views

06. 12. 2007
0 views

16. 12. 2007
0 views

18. 09. 2014
0 views

02. 10. 2014
0 views