23

I was asked a question in an interview to return 1 if provided 0 and return 0 if provided 1 without using conditions i.e if, ternary etc

Just to give you and idea below code without if's:

public int testMethod(int value){
    if(value==0) return 1;
    if(value==1) return 0;
    return 0;
}

Java Fiddle

UPDATE: Though @Usagi's Answer may seem the best fit with respect to the code I wrote .. but re-considering the question I re-analyzed the answers .. and @Sergio's answer seems the simplest and best fit ..

Rafay
  • 603
  • 2
  • 9
  • 24
  • Without using conditions? Meaning no `if` or ternary operators? – JNYRanger Aug 01 '17 at 13:10
  • 3
    @HelderSepu did you read the question? – Bender Bending Aug 01 '17 at 13:11
  • 1
    I updated your question to remove the language tags and made it language agnostic since the question doesn't say the language matters. Did the interviewer give you a language constraint? Otherwise @Usagi's answer is what I would have said. – JNYRanger Aug 01 '17 at 13:11
  • 3
    What if the input is neither 0 nor 1? – Eran Aug 01 '17 at 13:11
  • @JNYRanger no language constraint .. though they are a Java base company but they were testing my logic .. Yes indeed i tried Usagi's answer it correct .. will mark it so in a while .. – Rafay Aug 01 '17 at 13:16
  • 11
    Why was the now-deleted `return 1-value;` answer downvoted? With no specification of what to return for other input, that's completely correct and much simpler than the other answers. – Bernhard Barker Aug 01 '17 at 17:27
  • 5
    This is very much *not* language-agnostic, because any solution depends heavily on how the integer data type is implemented. (At least, in the case where the input is not 1 or 0 as the example implies.) – chepner Aug 01 '17 at 17:28
  • 5
    If you're expected to return 0 on other input, you should explicitly say so (in fact, you should probably clarify even if 0 and 1 are the only valid input values). At the moment one can assume either that return statement in your code is simply there to get your code to compile or that it's there to intentionally deal with the other inputs. – Bernhard Barker Aug 01 '17 at 17:32
  • @chepner I changed it back to language specific since all the answers use C# or Java anyways... – River Aug 01 '17 at 17:54
  • @Rafay please review my answer https://stackoverflow.com/questions/45438784/how-to-create-a-method-to-return-1-or-0-without-using-conditions/48360970#48360970 The answer is downvoted, but I do not understand why, because it works for all int numbers. – Alexander I. Jan 21 '18 at 19:30
  • @AlexanderI. Hello Alexander, I surely did not down-vote it ..maybe somebody spammed it .. – Rafay Jan 22 '18 at 07:28

18 Answers18

50

If you are given only 0 and 1 then this could be simpler:

return 1 - value;

Sergio Muriel
  • 1,039
  • 9
  • 15
27
public int testMethod(int value) {
  return 1 - (value % 2); // or 1 - (value & 1)
}

This could use to switch between any value and 0, EG 3:

public int testMethod3(int value) {
  return 3 - (value % 4);
}

And just to cover the return 0 at the end of the sample in the question:

private static final int[] VALUES = { 1, 0 };

public int testMethod(int value) {
    try {
        return VALUES[value];
    } catch (ArrayIndexOutOfBoundsException ex) {
        return 0;
    }
}
Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33
24

We can use the xor operator here. Xor is "exclusive or" and returns a 0 when there are two or zero 1's and returns 1 if there's exactly one 1. It does this on every bit of the integer.

So for example, the binary 1001 ^ 1000 = 0001 as the first bit has two 1's, so 0, the next two have no 1's, so zero, and the final bit only has one 1, outputting a 1.

public int testMethod(int value){
    return value ^ 1;
}
Louie Mayo
  • 349
  • 1
  • 4
13

My original answer

public int TestMethod(int value)
{
     return Convert.ToInt32(!Convert.ToBoolean(value));
}

and the modified one as suggested by @The Photon

public int TestMethod(int value)
{
     return Convert.ToInt32(value == 0);
}

A different approach is based on the behaviour of integer division in C# and avoiding the usage of exception handling.

public int TestMethod(int value)
{
    return 1 / ((10 * value) + 1);
}

All three methods will return the same results:

In | Out
-2 | 0 
-1 | 0
 0 | 1
 1 | 0
 2 | 0 
Martin Backasch
  • 1,829
  • 3
  • 20
  • 30
  • 3
    The only answer not ignoring the last `return 0;` – Guy Aug 01 '17 at 13:27
  • Alternate: `return Convert.ToInt32(value==0);` – The Photon Aug 01 '17 at 18:35
  • @ThePhoton `value==0` may hurts the constraint _'without using conditions i.e if, ternary etc condition'_ – Martin Backasch Aug 01 '17 at 20:06
  • 1
    @Martin, `if` and `?:` statements are conditional statements that produce branches in the control flow. `==` is just an operator that produces a result --- it can't produce any branch in the control flow unless used with a conditional like `if` or `?:` (or short-circuit `&&` or `||` or probably something else I'm forgetting). – The Photon Aug 01 '17 at 22:16
6

You can use a bitwise operator like so:

value ^ 1

^ is the bitwise XOR operator which "copies the bit if it is set in one operand but not both". The representation of 1 and 0 in bits is as follows:

1 = 0000 0001

0 = 0000 0000

So when value = 1 you end up doing:

1 ^ 1 = (0000 0001) ^ (0000 0001) = 0000 0000 = 0 because since they share the same bits none of the bits are copied over.

Now if value = 0 you end up doing:

0 ^ 1 = (0000 0000) ^ (0000 0001) = 0000 0001 = 1 because the last bit is 1 in one of the operands but 0 in the other.

Malphrush
  • 328
  • 3
  • 12
4

Assuming your language has something equivalent to get the absolute value of this number then something like:

public int testMethod(int value) {
  return Math.abs(value - 1);
}

would work.

mjwills
  • 23,389
  • 6
  • 40
  • 63
4

Alternatively, a try/catch function that divides 0/value.
- Function works without using any Math library;
- Function works with ALL Integer values;

public int MethodTest(int value)
{
     try
     {
         return (0/value);
     } 
     catch(Exception ex)
     {
         return 1;
     }
}

The choice of value is done by triggering a Compile Error:
A Zero divided by Zero usually triggers compile errors. Then returns 1;
A Zero divided any value different from Zero returns 0;

Arthur Zennig
  • 2,058
  • 26
  • 20
2

if there are no other inputs are allowed

    static int Test(int @value)
    {
        return (@value + 1) % 2;
    }
2

Please review my C# solution (.NET Fiddle):

private static int Calculate(int x)
{
    return ((-x ^ x) >> 31) + 1;
}

Examples:

Input: 0;           Output: 1;
Input: 1;           Output: 0;
Input: 64;          Output: 0;
Input: 65;          Output: 0;
Input: -100;        Output: 0;
Input: -101;        Output: 0;
Input: 102;         Output: 0;
Input: 888887;      Output: 0;
Input: 2147483647;  Output: 0;
Input: -2147483648; Output: 1;

It works for all int values (except int.MinValue).

Only logical and arithmetical operations without Math, Convert, etc. classes were used.

Explanation:

  • Execute XOR operator for input number x and negative input number -1 * x. Described XOR operator for C# is (-x ^ x)
  • XOR operator returns number with sign bit if x is non zero number (of course XOR with zero numbers returns 0)
  • The sign bit is a left bit of the number. Sign bit is the 32'nd bit for int number.
  • Execute right-shift operator and place sign bit on the first place for int number: (-x ^ x) >> 31
  • (-x ^ x) >> 31 returns -1 for any non zero int value (for zero number it returns 0)
  • Add 1 and return result

<iframe width="100%" height="475" src="https://dotnetfiddle.net/Widget/x4HCYj" frameborder="0"></iframe>
Alexander I.
  • 2,380
  • 3
  • 17
  • 42
1

Math.floor(1 / (1 + Math.abs(x)))

anonymous
  • 171
  • 5
1

I think the question is about calculate the bit-1 count.

public int testMethod(int value){
   //             v---  count = value == 0 ? 32 : [0,32)
   return Integer.bitCount(~value) / 32;
}

So the output should be as below:

//      v--- return 1
assert  testMethod(0) == 1; 

//      v--- return 0
assert  testMethod(nonZero) == 0; 
holi-java
  • 29,655
  • 7
  • 72
  • 83
1

considering inputs are only [1, 0] it is also possible to make method to return the 0 to the power of input

In java

public int test(int value){
    return Math.pow(0,value);
}

Same logic can be applied for any other language

Hatik
  • 1,139
  • 1
  • 15
  • 33
1

Using bitwise xor is probably the most computationally efficient way to do it

return value ^ 1

CodingPill
  • 31
  • 3
1

Number(!value)

it will return truthy or falsy value and converting it back into number, you will get 0 from 1 and 1 from 0.

K.Kaur
  • 91
  • 3
  • 8
0

String trickery!

Java:

public int testMethod(int value) {
    return String.valueOf(value).substring(0, 1).indexOf('0') + 1;
}

C#:

public int testMethod(int value) {
    return value.ToString().Substring(0, 1).IndexOf('0') + 1;
}

This relies on indexOf/IndexOf returning -1 if no match was found.

0

Given the range of value i is [0, 1]:

public int test(int i) {
    return !i;
}

This is pretty pointless...

Steve Fan
  • 3,019
  • 3
  • 19
  • 29
0

Not efficient, but interesting one:

public int neg(int n){
    return (int) Math.pow(0, n);
}
GooDeeJAY
  • 1,681
  • 2
  • 20
  • 27
-2

You are seeking some thing like this

var status = $_POST['status'];
status=='1'?'0':'1';
NaturalCoder
  • 128
  • 9