Java problems without using normal methods
1) Program to check whether the number is odd or even without using modulo or division operators.
The idea is to subtract 2 from the number until the number is less than 2. If the remaining value is 0, then number is odd, else even.
The idea is to subtract 2 from the number until the number is less than 2. If the remaining value is 0, then number is odd, else even.
public class oddeven {
public static void main(String args[])
{
int num =27;
if(odd(num))
System.out.println("ODD");
else
System.out.println("EVEN");
}
public static boolean odd(int num)
{ int temp=num;
while(temp>=2)
temp=temp-2;
if(temp==1)
return true;
else
return false;
}
}
2) Java program to return the maximum of two numbers without using if,while or for.
If 'a' and 'b' are 2 numbers, then the maximum value of a,b is (a+b)/2 + (|a-b|)/2. For one part we need to use floor and for the other part we need to use ceiling.
public class maxnum {
public static void main(String args[])
{
int num1=106;
int num2=121;
int max= findMax(num1,num2);
System.out.println(" Max value = " + max);
}
public static int findMax(int num1,int num2)
{
int diff=Math.abs(num1-num2);
int sum=num1+num2;
double diff1=(double)(diff);
double sum1= (double) (sum);
double result = Math.ceil(sum1/2)+Math.floor(diff1/2);
//double result = Math.ceil(diff1/2) + Math.floor(sum1/2);
int result1=(int)(result);
return result1;
}
}
Comments
Post a Comment