Toggle bits in the given range | Java implementation to toggle bits in the given range ; Function to toggle bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; toggle bits in the range l to r in ' n ' and return the number Besides this , we can calculate num as : num = ( 1 << r ) - l . ; driver program
import java . io . * ; class GFG { static int toggleBitsFromLToR ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return ( n ^ num ) ; } public static void main ( String [ ] args ) { int n = 50 ; int l = 2 , r = 5 ; System . out . println ( toggleBitsFromLToR ( n , l , r ) ) ; } }