Pergunta de entrevista da empresa Logikos, Inc.

How to determine if a provided number is even or odd without using mod operator, only using the integer type, and only using basic arithmetic operations (addition, subtraction, multiplication, division). (Completed on a whiteboard in front of two Principal Engineers).

Resposta da entrevista

Sigiloso

12 de jan. de 2016

A pseudo code answer was accepted for obvious reasons but I still tried to use c# syntax: // Result of 1 indicates even, 0 indicating odd public int IsEven(decimal num) { // This will truncate any decimal values // Only using integer type actually works to our advantage here int value = (int)num; // Since we have a whole number, we know that any odd value divided by 2 will not be an integer // However, since only using integer types, we know non-integers will be truncated int tempvalue = value / 2; // Testing to see if the tempvalue was truncated or not by multiplying it back by 2 and comparing to the original if (tempvalue * 2 == value) { // tempvalue was not truncated, hence even number return 1; } else { // tempvalue was truncated, so it is an odd number return 0; } }