least significant bit

Java Program To Check Least Significant Bit Of Number is Set or Not

Need to check the Least Significant bit is set or not. You are in the right place. I am going to explain how to check the least significant bit is set which means 1 or not set which means 0.

Example:

Let the number is 7 then it’s Binary will be 1 1 1 and the rightmost bit is known as the Least significant bit.

In above example right most bit is set i.e is 1.

I am going to discuss two ways of getting the Least significant bit is set or not.

Simple And Easy Way

The one of the easiest way is simply divide the number by 2 and check remainder, if remainder is 1 then bit will be set otherwise not set.

Fact: Why Divide by 2 gives you result

because when you divide by 2 you are in the first step of converting the number into binary and the remainder decides whether a bit is set or not

Least significant bit

import java.io.*;
import java.util.*;

class GeeksToCode {
	public static boolean check(int n)
	{
	    if( (n%2) == 0)
	    return  false;
	    else
	    return true;
	}
	
	
	public static void main (String[] args) {
		
		int t;
		Scanner s = new Scanner(System.in);
		t = s.nextInt();
		
		if(GeeksToCode.check(t))
		    System.out.println("Set");
		    else
		    System.out.println("Not Set");
		
	}

}

We simply use Scanner class to take input and then create a static method check() which takes one argument and tells us whether the bit is set or not. If the bit is set the check() methods return true else return false.

Input

7

Output

Set

Input

4

Output

Not Set

Simple And Easy Way 2.0

There is also another way of detecting whether the Left Most bit is set or not.

By using and with 1 and if result is 1 then left most bit is set otherwise not set. Let me explain you why

Suppose a number 12, Now it’s binary is

1 1 0 0

and take another number 13 and it’s binary is

1 1 0 1

Now examine both the binary of 12 and 13.

If you take the and of 12 with 1 what will you get

12 – 1 1 0 0

1 – 0 0 0 1

Result 0 0 0 0

If you take the and of 13 with 1 what will you get

131 1 0 1

1 – 0 0 0 1

Result 0 0 0 1

As you can see above 12 & 1 evaluate to 0. Since LSB of 12 is 0. Whereas, 13 & 1 evaluate to 1 since LSB of 13 is 1.

Code

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GeeksToCode {
	public static boolean check(int n)
	{
	    if( (n&2) == 0)
	    return  false;
	    else
	    return true;
	}
	
	
	public static void main (String[] args) {
		
		int t;
		Scanner s = new Scanner(System.in);
		t = s.nextInt();
		
		if(GeeksToCode.check(t))
		    System.out.println("Set");
		    else
		    System.out.println("Not Set");
		
	}

}

Check output here

Try Some more problems

Leave a Comment

Your email address will not be published. Required fields are marked *