Java lang.Long.lowestOneBit() method in Java with Examples (original) (raw)

Last Updated : 23 May, 2019

java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit position from right-1). If the binary expression does not contain any set bit, it returns 0.

Syntax:

public static long lowestOneBit(long num) Parameters: num - the number passed Returns: long value by only considering lowest 1 bit in the argument.

Examples:

Input : 36 Output : 4 Explanation: Binary Representation = 0010 0100 It considers lowest bit(at 3) and now reset rest of the bits i.e. 0000 0100 so result = 0100 i.e. 4 or in simple terms, the first set bit position from right is at position 3, hence 2^2=4

Input : 1032 Output : 8

The program below illustrates the java.lang.Long.lowestOneBit() function:

Program 1:

import java.lang.*;

public class GFG {

`` public static void main(String[] args)

`` {

`` long l = 1032 ;

`` System.out.println( "Lowest one bit = " + Long.lowestOneBit(l));

`` l = 45 ;

`` System.out.println( "Lowest one bit = " + Long.lowestOneBit(l));

`` }

}

Output:

Lowest one bit = 8 Lowest one bit = 1

Program 2: The program below demonstrates the use of function when a negative number is passed.

import java.lang.*;

public class GFG {

`` public static void main(String[] args)

`` {

`` long l = - 12 ;

`` System.out.println( "Binary = " + Long.toBinaryString(l));

`` System.out.println( "Lowest one bit = " + Long.lowestOneBit(l));

`` }

}

Output:

Binary = 1111111111111111111111111111111111111111111111111111111111110100 Lowest one bit = 4

It returns an error message when a decimal a string value is passed as an argument.

Program 3: When a decimal value is passed in argument.

import java.lang.*;

public class GFG {

`` public static void main(String[] args)

`` {

`` System.out.println( "Lowest one bit = " + Long.lowestOneBit( 12.34 ));

`` }

}

Output:

prog.java:12: error: incompatible types: possible lossy conversion from double to long System.out.println("Lowest one bit = " + Long.lowestOneBit(12.34));

Program 4: When a string value is passed in argument.

import java.lang.*;

public class GFG {

`` public static void main(String[] args)

`` {

`` System.out.println( "Lowest one bit = " + Long.lowestOneBit( "12" ));

`` }

}

Output:

prog.java:12: error: incompatible types: String cannot be converted to long System.out.println("Lowest one bit = " + Long.lowestOneBit("12"));