VOOZH about

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

⇱ Unset the last m bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Unset the last m bits

Last Updated : 15 Jun, 2022

Given a non-negative number n. The problem is to unset the last m bits in the binary representation of n.
Constraint: 1 <= m <= num, where num is the number of bits in the binary representation of n.

Examples: 

Input : n = 10, m = 2
Output : 8
(10)10 = (1010)2
(8)10 = (1000)2
The last two bits in the binary 
representation of 10 have been unset.

Input : n = 150, m = 4
Output : 144

Approach: Following are the steps: 

  1. Calculate num = (1 << (sizeof(int) * 8 – 1)) – 1. This will produce the highest positive integer num. All the bits in num will be set.
  2. Toggle the last m bits in num. Refer this post.
  3. Now, perform n = n & num. This will unset the last m bits in n.
  4. Return n.

Note: The sizeof(int) has been used as input is of int data type. For large inputs you can use long int or long long int datatypes in place of int

Output: 

144

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: