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:
- Calculate num = (1 << m) – 1. This will produce a number num having m bits and all will be set.
- Now, perform n = n ^ num. This will toggle the last m bits in n.
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int toggleLastMBits
(unsigned int n, unsigned int m)
{
unsigned int num = (1 << m) - 1;
return (n ^ num);
}
int main()
{
unsigned int n = 107;
unsigned int m = 4;
cout << toggleLastMBits(n, m);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG{
public static int toggleLastMBits
( int n, int m)
{
int num = ( 1 << m) - 1 ;
return (n ^ num);
}
public static void main(String argc[]){
int n = 107 ;
int m = 4 ;
n = toggleLastMBits(n, m);
System.out.println(n);
}
}
|
Python3
def toggleLastMBits(n,m):
num = ( 1 << m) - 1
return (n ^ num)
n = 107
m = 4
print (toggleLastMBits(n, m))
|
C#
using System;
namespace Toggle
{
public class GFG
{
public static int toggleLastMBits( int n, int m)
{
int num = (1 << m) - 1;
return (n ^ num);
}
public static void Main() {
int n = 107, m = 4;
n = toggleLastMBits(n, m);
Console.Write(n);
}
}
}
|
PHP
<?php
function toggleLastMBits( $n , $m )
{
$num = (1 << $m ) - 1;
return ( $n ^ $num );
}
{
$n = 107;
$m = 4;
echo toggleLastMBits( $n , $m );
return 0;
}
?>
|
Javascript
<script>
function toggleLastMBits(n, m)
{
var num = (1 << m) - 1;
return (n ^ num);
}
var n = 107;
var m = 4;
document.write( toggleLastMBits(n, m));
</script>
|
Output:
100
Time Complexity : O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...