+ 6
How we can find number is even or add without using arithmetic operations?
12 odpowiedzi
+ 18
Well, modulo is likely the best way,
but since you said no arithmetic operators:
(All code here is done with Java)
You could use bitwise & operator.
if num & 1 is 0, the number is even!
Example/
int input = 5;
boolean isEven = ((input & 1) == 0);
You can also use the shift operators.
For example,
int input = 5;
if((input >> 1) << 1 == input)
// Number is Even!
else
// Number is odd!
This works because if you shift back with an odd number you will lose some data! (The final binary digit will be cut off)
As for a very inefficient method (Time to get creatively not creative):
You could cast the number to a string and check if the last digit is an odd number.
Like:
int input = 501;
String num = String.valueOf(input);
char digit = num.charAt(num.length() - 1);
// last digit
if (digit == '1' || digit == '3' .... etc
As you can see, this is very impractical. But works!
+ 15
Maybe convert the number to a string and check if the last character is a 0, 2, 4, 6 or 8 for even, otherwise odd.
JS (regex): https://code.sololearn.com/W4v7H8KBY2f4/#js ;)
+ 6
@Rrestoring Maybe I'm wrong, but how could that even be possible for negatives? You're right about positives (num&1==1 or 0). But how could it be -1? Of course, I'm probably completely wrong...
+ 5
@A_Hook that's an awesome idea..
here is code of your idea in python
https://code.sololearn.com/cq2ax7ijfFuD/?ref=app
+ 4
it can be possible using bitwise operator. Check out this code in c++.
https://code.sololearn.com/cVKzKy66yBNk/?ref=app
+ 1
modulo operator will do it.
if (something % 2 == 0) will get an even number... else odd
why would you even consider without operators? your code would be terrible to look at.
+ 1
@ J.G
Nope, nvm I'm wrong about that.
Just tested it in AIDE, it didn't seem to make a difference. So I gues the & operator doesn't take sign into account. (I assumed it did, atleast for Java).
+ 1
if (n&1==1) odd
+ 1
@Muhammed, double "=" needed
+ 1
hey gaurav !according to me to find whether the no. is even or odd the best way is by doing programs on java
0
Well I understood this question as 'I want a negative but it looks like I'm subtracting something' and that's actually exactly what I suggest u do. Try, if u want -1, to do 1-2 instead, and then u can have ur negative number
0
There's a horror way also by multi-threading:
https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2Filp2013%2Fposts%2F1669269146457663&width=500