First and Last Three Bits | Java implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Converting n to binary ; Length of the array has to be at least 3 ; Convert first three bits to decimal ; Print the decimal ; Convert last three bits to decimal ; Print the decimal ; Driver code
import java . math . * ; public class GFG { static void binToDecimal3 ( int n ) { int a [ ] = new int [ 64 ] ; int x = 0 , i ; for ( i = 0 ; n > 0 ; i ++ ) { a [ i ] = n % 2 ; n /= 2 ; } x = ( i < 3 ) ? 3 : i ; int d = 0 , p = 0 ; for ( int j = x - 3 ; j < x ; j ++ ) d += a [ j ] * Math . pow ( 2 , p ++ ) ; System . out . print ( d + " ▁ " ) ; d = 0 ; p = 0 ; for ( int k = 0 ; k < 3 ; k ++ ) d += a [ k ] * Math . pow ( 2 , p ++ ) ; System . out . print ( d ) ; } public static void main ( String [ ] args ) { int n = 86 ; binToDecimal3 ( n ) ; } }