📜  在给定范围内切换位

📅  最后修改于: 2021-04-23 19:19:50             🧑  作者: Mango

给定一个非负数n和两个值lr 。问题在于将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

方法:以下是步骤:

  1. num计算=(((1 << r)– 1)^((1 <<(l-1))– 1)或((1 << r)-l)。这将产生一个具有r个位数的数字num ,并且范围lr的位是唯一的设置位。
  2. 现在,执行n = n ^ num 。这将在n的lr范围内切换位。
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