miss_M
miss_M

Reputation: 139

Write a method that get's 2 numbers as Input and return third different number

I'm struggling a bit with this question. You should return a different number without using ANY conditions / loop's in your code.

My way of thinking is that maybe the direction for the solution is using bit manipulation?

Upvotes: 1

Views: 364

Answers (3)

MrSmith42
MrSmith42

Reputation: 10151

If the two given numbers are:

  • input1
  • input2

You could simply return:

abs(intput1) +abs(input2) +1

You need to call abs() to avoid things like 1 + (-1) +1 = 1

Upvotes: 1

Paul Hankin
Paul Hankin

Reputation: 58339

((a&1)|(b&2))^3 is a number between 0 and 3 that differs from a in the first bit, and differs from b in the second bit. (This uses C notation: & is bitwise and, | is bitwise or, and ^ is bitwise xor).

Upvotes: 1

Henry
Henry

Reputation: 43778

To make sure the third number is different compose it by taking parts of the original numbers that have been changed. For example if the numbers are 123 and 789 you can take the "2" of the first number and make it a "3" and the "9" of the second number and make it a "0". Concatenate these two to get "30". This cannot be the first number because the second to last digit is different and it cannot be the second number because the last digit is different.

This can be formulated without loops and ifs (assuming integer arithmetic):

(a+10)/10%10*10 + (b+1)%10

Upvotes: 1

Related Questions