给定一个非负数n和两个值l和r 。问题在于将n的二进制表示形式的范围从l切换到r ,即,将比特从最右边的第l个比特切换到最右边的r个比特。切换操作将位0翻转为1 ,将位1翻转为0 。
约束: 1 <= l <= r <= n的二进制表示形式的位数。
例子:
Input : n = 17, l = 2, r = 3
Output : 23
(17)10 = (10001)2
(23)10 = (10111)2
The bits in the range 2 to 3 in the binary
representation of 17 are toggled.
Input : n = 50, l = 2, r = 5
Output : 44
方法:以下是步骤:
- 将num计算为=(((1 << r)– 1)^((1 <<(l-1))– 1)或((1 << r)-l)。这将产生一个具有r个位数的数字num ,并且范围l到r的位是唯一的设置位。
- 现在,执行n = n ^ num 。这将在n的l到r范围内切换位。
C/C++
// C++ implementation to toggle bits in
// the given range
#include
using namespace std;
// function to toggle bits in the given range
unsigned int toggleBitsFromLToR(unsigned int n,
unsigned int l, unsigned int r)
{
// calculating a number 'num' having 'r'
// number of bits and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// toggle bits in the range l to r in 'n'
// and return the number
//Besides this, we can calculate num as: num=(1<
Java
// Java implementation to toggle bits in
// the given range
import java.io.*;
class GFG
{
// Function to toggle bits in the given range
static int toggleBitsFromLToR(int n, int l, int r)
{
// calculating a number 'num' having 'r'
// number of bits and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// toggle bits in the range l to r in 'n'
// and return the number
//Besides this, we can calculate num as: num=(1<
Python3
# Python implementation
# to toggle bits in
# the given range
# function to toggle bits
# in the given range
def toggleBitsFromLToR(n,l,r):
# calculating a number
# 'num' having 'r'
# number of bits and
# bits in the range l
# to r are the only set bits
num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
# toggle bits in the
# range l to r in 'n'
# Besides this, we can calculate num as: num=(1<
C#
// C# implementation to toggle bits
// in the given range
using System;
namespace Toggle
{
public class GFG
{
// Function to toggle bits in the given range
static int toggleBitsFromLToR(int n, int l, int r)
{
// calculating a number 'num' having 'r'
// number of bits and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// toggle bits in the range l to r in 'n'
//Besides this, we can calculate num as: num=(1<
PHP
输出:
44