Implement IsOdd function in Java

Information about Implement IsOdd function in Java

Published on November 30, 2007

Author: rohitsghatol

Source: authorstream.com

Content

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!!

Related presentations


Other presentations created by rohitsghatol

What is Java?
30. 11. 2007
0 views

What is Java?

Golden Brick Problem
30. 11. 2007
0 views

Golden Brick Problem

Google ajax search to the rescue
16. 12. 2007
0 views

Google ajax search to the rescue