VOOZH about

URL: https://www.geeksforgeeks.org/dsa/toggle-last-m-bits/

⇱ Toggle the last m bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toggle the last m bits

Last Updated : 31 May, 2022

Given a non-negative number n. The problem is to toggle the last m bits in the binary representation of n. A toggle operation flips a bit from 0 to 1 and a bit from 1 to 0.
Constraint: 1 <= m <= n.


Examples: 

Input : n = 21, m = 2
Output : 22
(21)10 = (10101)2
(22)10 = (10110)2
The last two bits in the binary
representation of 21 are toggled.

Input : n = 107, m = 4
Output : 100 

Approach: Following are the steps: 

  1. Calculate num = (1 << m) - 1. This will produce a number num having m bits and all will be set.
  2. Now, perform n = n ^ num. This will toggle the last m bits in n.

Output: 

100

Time Complexity : O(1)

Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: