VOOZH about

URL: https://www.geeksforgeeks.org/aptitude/programming-puzzle-assign-value-without-control-statement/

⇱ Programming puzzle (Assign value without any control statement) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Programming puzzle (Assign value without any control statement)

Last Updated : 20 Jul, 2022

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).

Examples : 

Input : a = 3, b = 7, x = 1
Output : y = 7

Input : a = 3, b = 7, x = 0
Output : y = 3

The idea is to create an array of size two where the first element is 'a' and the second element is 'b'. We use x as an index in the array.

Implementation:


Output
3

Time complexity : O(1) 
Auxiliary Space : O(1)

Alternate Solution: 


Output
3

Time complexity : O(1) 
Auxiliary Space : O(1)

Thanks to Forrest Smith for suggesting the above solution.
 

Comment
Article Tags: