-1

how can we figure-out a number is even or odd, with out using division(/) or percentile (%) symbols.

This one of the interview asked to me. Asked me to write program using java.

We should not use arithmetic symbols like division(/) , percentile (%).

Tobia Tesan
  • 1,938
  • 17
  • 29
Eswar Goud
  • 134
  • 1
  • 11

3 Answers3

7

Without using division or modulo, the only thing that comes to mind is checking if the last digit is in the set [ 1, 3, 5, 7, 9 ], like so:

public static boolean isEven(int testNumber) {

  String strI = Integer.toString(testNumber);
  String lastCharacter = strI.substring(strI.length() - 1);
  return ("13579".indexOf(lastCharacter) == -1);

}

That would produce:

System.out.println ( isEven( 10) );  // true
System.out.println ( isEven( 11) );  // false
System.out.println ( isEven( 999) ); // false

Good enough?

Graham Charles
  • 9,394
  • 3
  • 26
  • 41
  • Excellent answer, it works for me. Thank you so much!!! – Eswar Goud Sep 01 '15 at 07:42
  • Although I'm reasonably sure that to generate a string representation toString *does* use division and modulo. Shouldn't @AmirPashazadeh's be the accepted answer, since pure bit shifting should not involve division? – Tobia Tesan Sep 02 '15 at 13:44
  • I think you're right but not for that reason. OP said don't "use arithmetic symbols like division(/) , percentile (%)" -- so toString is legit within those parameters (not using "the symbols"). But -- that "like" means that the exercise was probably to avoid *all* arithmetical symbols, so I failed with my "-". – Graham Charles Sep 03 '15 at 15:08
4

Shift right and then shift left the number, if it remains the same number is even, otherwise it is odd.

Amir Pashazadeh
  • 7,170
  • 3
  • 39
  • 69
2
boolean isOdd = (yourInteger&1)==1;

That is from the link provided by Christopher How do I check if an integer is even or odd?

Community
  • 1
  • 1
matt
  • 10,892
  • 3
  • 22
  • 34
  • That link also indicates that this technique doesn't work universally for negative numbers (in c, anyway). Thoughts? – Graham Charles Sep 02 '15 at 05:50
  • 1
    Java always uses twos complement, so it should always work. Even with the other integer data types. – matt Sep 02 '15 at 06:13