Check Oddity
Write the precise code to check the number is Odd or not.
Approach#1
Check the module 2 of number is Zero. If it Zero, number is Odd.
public boolean oddOrNot(int num) {
return num % 2 == 1;
}
Problem: It will not return the correct result for the negative number.
Approach#2
If number is positive/negative, Subtract 2/-2 from number respectively until the number result is Zero or one.
public boolean oddOrNot(intnum) {
int s = 0;
if(num>0) {
s = 2;
} else {
s = -2;
}
while(num>1) {
num = num – s;
}
if(num==0) {
return false;
} else {
return true;
}
}
Complexity of given approach is O(num).
Approach#3
Example:Number = 10
Binary representation of 10 = 1010
Binary representation of 1 = 0001
Logical AND of both numbers = 0000.
A number will be Odd iff last bit of binary representation is 1.
public boolean oddOrNot(intnum) {
return (num & 1) != 0;
}
This is highly optimized code. Since, Arithmetic and Logical operations are much faster compared to division and multiplication.
No comments:
Post a Comment