Assign other value to a variable from two possible values
Last Updated :
06 Mar, 2023
Suppose a variable x can have only two possible values a and b, and you wish to assign to x the value other than its current one. Do it efficiently without using any conditional operator.
Note: We are not allowed to check current value of x.
Examples:
Input : a = 10, b = 15, x = a
Output : x = 15
Explanation x = 10, currently x has value of a (which is 10), we need to change it to 15.
Input : a = 9, b = 11, x = b
Output : x = 9
We could solve this problem using if condition, but we are not allowed to do that.
if (x == a)
x = b;
else x = a;
We could have used Ternary operator, it also checks the current value of x and based on that it assigns new value. So we cannot use this approach as well
x = x == a ? b : a;
But, we are not allowed to check value of x, so none of the above solutions work.
Solution 1: Using arithmetic operators only we can perform this operation
x = a + b - x
This way the content of x will alternate between a and b every time it gets executed
C++
// CPP program to change value of x
// according to its current value.
#include <bits/stdc++.h>
using namespace std;
// Function to alternate the values
void alternate(int& a, int& b, int& x)
{
x = a + b - x;
}
// Main function
int main()
{
int a = -10;
int b = 15;
int x = a;
cout << "x is : " << x;
alternate(a, b, x);
cout << "\nAfter change ";
cout << "\nx is : " << x;
}
Java
// Java program to change value of x
// according to its current value.
import java.util.*;
class solution
{
// Function to alternate the values
static void alternate(int a, int b, int x)
{
x = a + b - x;
System.out.println("After change"+"\n"+" x is : "+x);
}
// Main function
public static void main(String args[])
{
int a = -10;
int b = 15;
int x = a;
System.out.println("x is : "+x);
alternate(a, b, x);
}
}
Python3
# Python3 program to change value
# of x according to its current value.
# Function to alternate the values
def alternate(a,b,x):
x = a+b-x
print("After change x is:",x)
# Driver code
if __name__=='__main__':
a = -10
b = 15
x = a
print("x is:",x)
alternate(a,b,x)
# This code is contributed by
# Shrikant13
C#
// C# program to change value of x
// according to its current value.
using System;
class gfg
{
// Function to alternate the values
public void alternate(ref int a, ref int b, ref int x)
//'ref' indicates the references
{
x = a + b - x;
}
}
// Main function
class geek
{
public static int Main()
{
gfg g = new gfg();
int a = -10;
int b = 15;
int x = a;
Console.WriteLine("x is : {0}" , x);
g.alternate(ref a, ref b, ref x);
Console.WriteLine ("After change ");
Console.WriteLine("x is : {0}", x);
return 0;
}
}
//This code is contributed by Soumik
PHP
<?php
// PHP program to change value of x
// according to its current value.
// Function to alternate the values
function alternate (&$a, &$b, &$x)
{
$x = $a + $b - $x;
}
// Driver Code
$a = -10;
$b = 15;
$x = $a;
echo "x is : ", $x;
alternate($a, $b, $x);
echo "\nAfter change ";
echo "\nx is : ", $x;
// This code is contributed by ajit.
?>
JavaScript
<script>
// javascript program to change value of x
// according to its current value.
// Function to alternate the values
function alternate(a , b , x) {
x = a + b - x;
document.write("After change" + "<br/>" + " x is : " + x);
}
// Main function
var a = -10;
var b = 15;
var x = a;
document.write("x is : " + x+"<br/>");
alternate(a, b, x);
// This code is contributed by todaysgaurav
</script>
Output: x is : -10
After change
x is : 15
Time Complexity: The time complexity of this approach is O(1)
Space Complexity: The space complexity of this approach is O(1)
Solution 2: A better and efficient approach is using the bitwise XOR operation.
x = a^b^x
C++
// CPP program to change value of x
// according to its current value.
#include <bits/stdc++.h>
using namespace std;
// Function to alternate the values
void alternate(int& a, int& b, int& x)
{
x = a ^ b ^ x;
}
// Main function
int main()
{
int a = -10;
int b = 15;
int x = a;
cout << "x is : " << x;
alternate(a, b, x);
cout << "\nAfter exchange ";
cout << "\nx is : " << x;
return 0;
}
Java
// Java program to change value of x
// according to its current value.
class GFG {
// Function to alternate the values
static int alternate(int a, int b, int x) {
return x = a ^ b ^ x;
}
// Main function
public static void main(String[] args) {
int a = -10;
int b = 15;
int x = a;
System.out.print("x is : " + x);
x = alternate(a, b, x);
System.out.print("\nAfter exchange ");
System.out.print("\nx is : " + x);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to change value of x
# according to its current value.
# Function to alternate the values
def alternate(a, b, x):
x = a ^ b ^ x
print("After exchange")
print("x is", x)
# Driver code
a = -10
b = 15
x = a
print("x is", x)
alternate(a, b, x)
# This code is contributed
# by Shrikant13
C#
// C# program to change value of x
// according to its current value.
using System;
public class GFG {
// Function to alternate the values
static int alternate(int a, int b, int x) {
return x = a ^ b ^ x;
}
// Main function
public static void Main() {
int a = -10;
int b = 15;
int x = a;
Console.Write("x is : " + x);
x = alternate(a, b, x);
Console.Write("\nAfter exchange ");
Console.Write("\nx is : " + x);
}
}
/*This code is contributed by Rajput-Ji*/
PHP
<?php
// PHP program to change value of x
// according to its current value.
// Function to alternate the values
function alternate(&$a, &$b, &$x)
{
$x = $a ^ $b ^ $x;
}
// Driver Code
$a = -10;
$b = 15;
$x = $a;
echo "x is : ", $x;
alternate($a, $b, $x);
echo "\nAfter exchange ";
echo "\nx is : ", $x;
// This code is contributed
// by akt_mit
?>
JavaScript
<script>
// Javascript program to change value of x
// according to its current value.
// Function to alternate the values
function alternate(a , b , x) {
return x = a ^ b ^ x;
}
// Main function
var a = -10;
var b = 15;
var x = a;
document.write("x is : " + x);
x = alternate(a, b, x);
document.write("<br/>After exchange ");
document.write("<br/>x is : " + x);
// This code contributed by Rajput-Ji
</script>
Output: x is : -10
After exchange
x is : 15
Time Complexity: The time complexity of this approach is O(1)
Space Complexity: The space complexity of this approach is O(1)
Solution 3:
Using the multiplication operator, we can perform the operation:
x = a * b / x
This way the content of x will alternate between a and b.
This approach has only one step:
Step 1: x = a * b / x
C++
// CPP program to change value of x
// according to its current value.
#include <bits/stdc++.h>
using namespace std;
// Function to alternate the values
void alternate(int& a, int& b, int& x)
{
x = a * b / x;
}
// Main function
int main()
{
int a = -10;
int b = 15;
int x = a;
cout << "x is : " << x;
alternate(a, b, x);
cout << "\nAfter change ";
cout << "\nx is : " << x;
}
//This code is contributed by phasing17
Java
import java.util.*;
public class Main {
// Function to alternate the values
public static int alternate(int a, int b, int x) {
x = a * b / x;
return x;
}
// Main function
public static void main(String[] args) {
int a = -10;
int b = 15;
int x = a;
System.out.println("x is : " + x);
x=alternate(a, b, x);
System.out.println("\nAfter change ");
System.out.println("x is : " + x);
}
}
Python3
# Function to alternate the values
def alternate(a, b, x):
x = a * b // x
return x
# Main function
def main():
a = -10
b = 15
x = a
print("x is :", x)
x = alternate(a, b, x)
print("\nAfter change ")
print("x is :", x)
if __name__ == '__main__':
main()
C#
// C# program to change value of x
// according to its current value.
using System;
public class Program
{
// Function to alternate the values
static void alternate(ref int a, ref int b, ref int x)
{
x = a * b / x;
}
// Main function
public static void Main()
{
int a = -10;
int b = 15;
int x = a;
Console.WriteLine("x is : " + x);
alternate(ref a, ref b, ref x);
Console.WriteLine("\nAfter change ");
Console.WriteLine("x is : " + x);
}
}
// This code is contributed by bhardwajji
JavaScript
// JavaScript program to change value of x
// according to its current value.
// Function to alternate the values
function alternate(a, b,x )
{
x = a * b / x;
return x;
}
// Main function
let a = -10;
let b = 15;
let x = a;
console.log("x is : " + x);
x = alternate(a, b, x);
console.log("After change ");
console.log("x is : " + x);
// This code is contributed by phasing17
Output:
x is : -10
After exchange
x is : 15
Time Complexity: The time complexity of this approach is O(1)
Auxiliary Space: The space complexity of this approach is O(1)
Similar Reads
Javascript program to swap two numbers without using temporary variable To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable. Below are the approaches used to swap two numbers without using a temporary variable: Table of Content Using Arithme
6 min read
Programming puzzle (Assign value without any control statement) Given four integers 'a', 'b', 'y' and 'x', where 'x' can only be either zero or one. Your task is as follows: If 'x' is zero assign value 'a' to the variable 'y'If 'x' is one assign value 'b' to the variable 'y'. It is not allowed to use any conditional operator (including the ternary operator). Exa
6 min read
Assigning multiple variables in one line in Python A variable is a segment of memory with a unique name used to hold data that will later be processed. Although each programming language has a different mechanism for declaring variables, the name and the data that will be assigned to each variable are always the same. They are capable of storing val
2 min read
Check if it is possible to assign values such that all the given relations are satisfied Given an array of strings arr[], where each arr[i] is of the form "i==j" or "i!=j", where i and j are variables representing relationships among them, the task is to check if it is possible to assign values to the variables that satisfy all the relations. If found to be true, then print "Yes". Other
10 min read
XOR of Two Variables in Python The XOR or exclusive is a Boolean logic operation widely used in cryptography and generating parity bits for error checking and fault tolerance. The operation takes in two inputs and produces a single output. The operation is bitwise traditionally but could be performed logically as well. This artic
6 min read
Create an array filled with given values Using JavaScript In JavaScript, an array is a collection of values that can be stored and accessed in a single variable. Each value in an array is called an element, and elements can be of any data type, such as numbers, strings, or other objects. Arrays are indexed, meaning that each element has a numerical positio
5 min read
Change bits to make specific OR value Given two positive integers A and B, we can change at most K bits in both the numbers to make OR of them equal to a given target number T. In the case of multiple solutions try to keep A as small as possible. Examples : Input : A = 175, B = 66, T = 100, K = 5 Output : A = 36 B = 64 Initial bits of A
15 min read
Find if the Vacation can be taken or not Given are the following values: N which are the number of days left for the exams.S which are the number of subjects to be prepared for the exam.C which are the number of chapters to be prepared for each subject.H which are the number of hours to prepare a chapter.L which are the number of days of d
7 min read
Write a function that returns 2 for input 1 and returns 1 for 2 Write a function which returns 1 that 2 is passed and return 2 when 1 is passed.Source: Adobe Interview Experience | Set 19 (For MTS)A simple solution is to compare the passed value with 1 and 2. C int invert(int x) { if (x == 1) return 2; else return 1; } Java static int invert(int x) { if (x == 1)
3 min read
Find the number of Enjoyable Chocolates for Geek's Budget Geek has gone to a chocolate shop with exactly k coins in his pocket. The shop offers a selection of n chocolates, each with a unique, sorted (in increasing order) price. Geek's goal is to enjoy the costliest chocolates he can afford. However, he is shy and doesn't want to ask the shopkeeper about t
14 min read