给定一个非负数n 。问题是要切换n的二进制表示形式中的最后m位。切换操作将位0翻转为1 ,将位1翻转为0 。
约束: 1 <= m <= n。
例子:
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
方法:以下是步骤:
- 计算num =(1 << m)–1。这将生成具有m个位数的数字num ,并且将全部设置。
- 现在,执行n = n ^ num 。这将切换n中的最后m位。
C++
// C++ implementation to
// toggle the last m bits
#include
using namespace std;
// function to toggle
// the last m bits
unsigned int toggleLastMBits
(unsigned int n, unsigned int m)
{
// calculating a number
// 'num' having 'm' bits
// and all are set.
unsigned int num = (1 << m) - 1;
// toggle the last m bits
// and return the number
return (n ^ num);
}
// Driver code
int main()
{
unsigned int n = 107;
unsigned int m = 4;
cout << toggleLastMBits(n, m);
return 0;
}
Java
// Java implementation to
// toggle the last m bits
import java.util.*;
import java.lang.*;
public class GfG{
// function to toggle
// the last m bits
public static int toggleLastMBits
(int n, int m)
{
// calculating a number
// 'num' having 'm' bits
// and all are set
int num = (1 << m) - 1;
// toggle the last m bits
// and return the number
return (n ^ num);
}
// Driver function
public static void main(String argc[]){
int n = 107;
int m = 4;
n = toggleLastMBits(n, m);
System.out.println(n);
}
}
// This code is contributed by Sagar Shukla.
Python3
# Python implementation to
# toggle the last m bits
# function to toggle
# the last m bits
def toggleLastMBits(n,m):
# calculating a number
# 'num' having 'm' bits
# and all are set.
num = (1 << m) - 1
# toggle the last m bits
# and return the number
return (n ^ num)
# Driver code
n = 107
m = 4
print(toggleLastMBits(n, m))
# This code is contributed
# by Anant Agarwal.
C#
// C# implementation to
// toggle the last m bits
using System;
namespace Toggle
{
public class GFG
{
// Function to toggle the last m bits
public static int toggleLastMBits(int n, int m)
{
// Calculating a number 'num' having
// 'm' bits and all are set
int num = (1 << m) - 1;
// Toggle the last m bits
// and return the number
return (n ^ num);
}
// Driver Code
public static void Main() {
int n = 107, m = 4;
n = toggleLastMBits(n, m);
Console.Write(n);
}
}
}
// This code is contributed by Sam007.
PHP
输出:
100