For every set bit of a number toggle bits of other
Given two integer numbers, whenever the bits of the first number is set i.e. 1, toggle the bits of the second number leaving the rest bits of the second number unchanged.
Examples :
Input: 2 5
Output: 7
2 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. 111
Input: 1 3
Output: 2
Approach:
Just do XOR of the given two Number.
C++
#include <bits/stdc++.h>
using namespace std;
int toggleBits( int n1, int n2)
{
return n1 ^ n2;
}
int main()
{
int n1 = 2, n2 = 5;
cout << toggleBitst(n1, n2) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int toggleBits( int n1, int n2)
{
return (n1 ^ n2);
}
public static void main(String args[])
{
int n1 = 2 , n2 = 5 ;
System.out.println(toggleBits(n1, n2));
}
}
|
Python3
def toggleBits(n1, n2) :
return (n1 ^ n2)
n1 = 2
n2 = 5
print (toggleBits(n1, n2))
|
C#
using System;
class GFG {
static int toggleBits( int n1, int n2)
{
return (n1 ^ n2);
}
public static void Main()
{
int n1 = 2, n2 = 5;
Console.WriteLine(toggleBits(n1, n2));
}
}
|
PHP
<?php
function toggleBits( $n1 , $n2 )
{
return $n1 ^ $n2 ;
}
$n1 = 2;
$n2 = 5;
echo toggleBits( $n1 , $n2 ). "\n" ;
?>
|
Javascript
<script>
function toggleBits(n1, n2)
{
return (n1 ^ n2);
}
let n1 = 2, n2 = 5;
document.write(toggleBits(n1, n2));
</script>
|
Output :
7
Time Complexity : O(1)
Auxiliary Space: O(1)
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...