Testing even numbers in Java without a modular operator

How do I do this in Java? Find if the number is divisible by 2, if the last digit is even. (0,2,4,6,8) Example: 128, 129 is not

+8
java syntax bit-manipulation logic
source share
7 answers

Use bitwise control and

 if( (number&1) == 0) 

Bitwise operator AND <

The and operator (bitwise AND) compares each bit of its first operand with the corresponding bit of the second operand. If both bits are 1, the corresponding bit of the result is set to 1. Otherwise, it sets the corresponding bit of the result to 0 ( source ).

In binary format, even numbers have the least significant bit equal to zero . knowing this and using the operator and, you can find out whether it is uniform or not.

Therefore, it takes the number ..abcdy and compares with .00001 if y is zero, and..abcdy and ..00001 is also zero, thus an even number.

+14
source share

see, if the rightmost bit is 1, then it is not, using bitwise operators

execute boolean and with (for example)

 yourNumber & 1 
+5
source share

Check low bit:

 boolean even = (x & 1) == 0; 

LSB 0 for an even number and 1 for odd numbers, just as for decimal numbers, the least significant digit is 0 if it is divisible by 10 .

+5
source share

Myway;)

public class Even_Odd {

 /** * @param args */ public static void main(String[] args) { int val=550; // TODO Auto-generated method stub while(val>=0) { if(val==1) { System.out.println("Odd Number"); } else if(val==0) { System.out.println("Even Number"); } val=val-2; // System.out.println(val); } } 

}

0
source share
 if((n|1)==n) System.out.println("odd"); else System.out.println("even"); 

Reason: the number is odd if the LSB is 1, and even otherwise. When n | 1 is executed, the odd-value LSB remains the same, so the resulting number does not change, and the even-number LSB becomes 1, thereby changing the number.

0
source share

Divide the number by 2 and multiply the answer 2 , if you get your original number, then the number β€œEven” , if not, then the number β€œOdd”

 public class EvenOrOdd { public static void main(String args[]) { int value = 129; if((value/2)*2==value) { System.out.println("The Given Number \""+value+"\" is Even"); } else { System.out.println("The Given Number \""+value+"\" is Odd"); } } } 
0
source share
 import java.io.*; import java.util.*; public class CheckNumber{ public static void main(String... args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter the number to check even or odd"); int number=Integer.parseInt(br.readLine()); String temp=number+""; //convert number to string char ch=temp.charAt(temp.length()-1); //get last character temp=ch+""; if(temp.equals("0") || temp.equals("2") || temp.equals("4") || temp.equals("6") || temp.equals("8")) //check last number is even System.out.println("Number is even"); else System.out.println("Number is odd"); } 

}

0
source share

All Articles