对于一个数字的每一个设定位,切换其他的位

给定两个整数,每当第一个数字的位设置为1时,切换第二个数字的位,保持第二个数字的其余位不变。

null

例如:

Input: 2 5Output: 72 is represented as 10 in binary and 5 is represented as 101. Hence toggling the 2nd bit of 5 from right, thus the new number becomes 7 i.e. 111Input: 1 3Output: 2

方法: 对给定的两个数进行异或运算。

C++

// A CPP program toggle bits of n2
// that are at same position as set
// bits of n1.
#include <bits/stdc++.h>
using namespace std;
// function for the Nega_bit
int toggleBits( int n1, int n2)
{
return n1 ^ n2;
}
// Driver program to test above
int main()
{
int n1 = 2, n2 = 5;
cout << toggleBitst(n1, n2) << endl;
return 0;
}


JAVA

// A Java program toggle bits of n2
// that are at same position as set
// bits of n1.
import java.io.*;
class GFG {
// function for the Nega_bit
static int toggleBits( int n1, int n2)
{
return (n1 ^ n2);
}
// Driver program
public static void main(String args[])
{
int n1 = 2 , n2 = 5 ;
System.out.println(toggleBits(n1, n2));
}
}
// This code is contributed
// by Nikita Tiwari.


Python3

# A Python 3 program toggle bits of n2
# that are at same position as set
# bits of n1.
# function for the Nega_bit
def toggleBits(n1, n2) :
return (n1 ^ n2)
# Driver program to test above
n1 = 2
n2 = 5
print (toggleBits(n1, n2))
# This code is contributed
# by Nikita Tiwari.


C#

// C# program toggle bits of n2
// that are at same position as set
// bits of n1.
using System;
class GFG {
// function for the Nega_bit
static int toggleBits( int n1, int n2)
{
return (n1 ^ n2);
}
// Driver program
public static void Main()
{
int n1 = 2, n2 = 5;
Console.WriteLine(toggleBits(n1, n2));
}
}
// This code is contributed by Anant Agarwal.


PHP

<?php
// PHP program to toggle bits of n2
// that are at same position as set
// bits of n1.
// function for the Nega_bit
function toggleBits( $n1 , $n2 )
{
return $n1 ^ $n2 ;
}
// Driver code
$n1 = 2;
$n2 = 5;
echo toggleBits( $n1 , $n2 ). "" ;
// This code is contributed by mits
?>


Javascript

<script>
// JavaScript program toggle bits of n2
// that are at same position as set
// bits of n1
// Function for the Nega_bit
function toggleBits(n1, n2)
{
return (n1 ^ n2);
}
// Driver code
let n1 = 2, n2 = 5;
document.write(toggleBits(n1, n2));
// This code is contributed by sanjoy_62
</script>


输出:

7

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享