-1

yesterday i went to an interview i was asked a question which is below

Create an input field and button user should enter only 0 or 1 when the user enters 0 the output should be 1. when the user enters 1 the output should be 0. Write the logic of minimum 5 possible way of the output?

Note:

We should not use any if,for,while,do while,if else,switch,.. (no condition and loops) should be used.

It should be done in java script and minimum 5 possible way to print the out .

I don't know whether it is possible or not for 5 times. if any one knows please help me

Mohan Gopi
  • 7,606
  • 17
  • 66
  • 117
  • Most likely they mean to use the truthy/falsy properties of JavaScript. Look for the solution in that direction. – meskobalazs May 25 '16 at 10:43
  • Beside that you should at least show something you have tried and/or some thoughts about it. `user **should** enter only` can the user enter something else then `0` or`1`, if so what should be the output for an input that is not `0` or `1`. `Write the logic of minimum 5 possible way of the output` what does this mean? What are the _different way of output_ . – t.niese May 25 '16 at 10:45
  • do you have to take restrictions about what user type or we know that always he'll type what expected? –  May 25 '16 at 10:48
  • @t.niese he probably means to find 5 different solutions. –  May 25 '16 at 10:49
  • @t.niese no the user should enter only 0 and 1. we should print the same output with minimum of diffrent ways but the output should be same when user enters 0 and click the button the output should be 1. like that – Mohan Gopi May 25 '16 at 10:49
  • @meskobalazs actully i did not get anything in my mind so i left that question. – Mohan Gopi May 25 '16 at 10:51
  • @GeorgeGkas no user should type only 0 or 1 – Mohan Gopi May 25 '16 at 10:54
  • 1
    Here are many different ways how you could do it: [Is there a better way of writing v = (v == 0 ? 1 : 0);](http://stackoverflow.com/questions/6911235/is-there-a-better-way-of-writing-v-v-0-1-0) including array, bitwise, modulo, comparison, .... – t.niese May 25 '16 at 10:55
  • @WaKai so you only read the title of the question, without taking a look at the answers? – t.niese May 25 '16 at 10:57
  • @t.niese thanks may be that can help me – Mohan Gopi May 25 '16 at 11:01

1 Answers1

0

One possibility is to use bitwise operators:

console.log(~ document.getElementById('input_field').value + 2 );

~ Inverts the bits, so you will get -2 for the input 1 and -1 for the input 0. Then just add 2 to get your result.

Edit #2:

console.log(document.getElementById('input_field').value ^ 1);

Using the XOR (^) Operator.

Edit #3:

Plain simple, just subtract the input from 1:

console.log(1 - document.getElementById('input_field').value);
Wa Kai
  • 466
  • 5
  • 12