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

11
  • 3
    @HelderSepu did you read the question?
    – Ubernator
    Aug 1, 2017 at 13:11
  • 3
    What if the input is neither 0 nor 1?
    – Eran
    Aug 1, 2017 at 13:11
  • 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. Aug 1, 2017 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 1, 2017 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. Aug 1, 2017 at 17:32

18 Answers 18

51

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

return 1 - value;

4
  • 6
    Wow, great solution.
    – mjwills
    Aug 1, 2017 at 22:11
  • The simplest things are the most beautiful
    – ESR
    Aug 2, 2017 at 4:40
  • ok i was banging my head on the wrong door .. this is a beautiful answer ..
    – Rafay
    Aug 4, 2017 at 12:15
  • I had abs(value-1) but this is simpler and much more elegant. Jun 5, 2022 at 19:33
28
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;
    }
}
2
  • 2
    Doh, you beat me to it!
    – JNYRanger
    Aug 1, 2017 at 13:11
  • Oh nice .. never thought of it this way .. :)
    – Rafay
    Aug 1, 2017 at 13:14
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;
}
2
  • 3
    I think this is the better answer since XOR is logically equivalent to the inequality operator when operating on boolean values. Aug 1, 2017 at 16:09
  • 2
    This does not give the same answer as the original code for inputs other than 0 and 1.
    – The Photon
    Aug 1, 2017 at 18:33
14

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 
4
  • 3
    The only answer not ignoring the last return 0;
    – Guy
    Aug 1, 2017 at 13:27
  • Alternate: return Convert.ToInt32(value==0);
    – The Photon
    Aug 1, 2017 at 18:35
  • @ThePhoton value==0 may hurts the constraint 'without using conditions i.e if, ternary etc condition' Aug 1, 2017 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 1, 2017 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.

2
  • 2
    Consider inputs other than 0 or 1.
    – The Photon
    Aug 1, 2017 at 18:36
  • 2
    @ThePhoton: That wasn't the spec given by the op. Aug 1, 2017 at 19:51
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.

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;

0
3

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>

1
  • Hello Alexander, I surely did not down-vote it ..maybe somebody spammed it .
    – Rafay
    Jan 22, 2018 at 7:28
1

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

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; 
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

1

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

return value ^ 1

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.

2
  • method returns int not boolean
    – Rafay
    Mar 16, 2020 at 6:53
  • (!value) returns boolean and you can convert that back to a number which is what Number function is doing here
    – K.Kaur
    Mar 16, 2020 at 18:56
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...

1
  • 1
    Can you specify the language you are using. This will not compile in C# nor Java. Oct 13, 2017 at 8:33
0

Not efficient, but interesting one:

public int neg(int n){
    return (int) Math.pow(0, n);
}
-2

You are seeking some thing like this

var status = $_POST['status'];
status=='1'?'0':'1';
1
  • 1
    without using conditions i.e if, ternary etc. Your solution uses ternary operators
    – Rafay
    Jan 6, 2020 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.