Hi,
I was recently asked to write a program, that determines whether a number is even or odd without using any mathematical/bitwise operator!
Any ideas?
Thanks!
Hi,
I was recently asked to write a program, that determines whether a number is even or odd without using any mathematical/bitwise operator!
Any ideas?
Thanks!
You could convert the number into a string and check if the last digit is 1,3,5,7 or 9.
I'm not sure if == is considered as a math operator, if no, then convert the number to a string and test if the last char is equal to 0, 2, 4, 6 or 8.
Edit: == seems to be considered as a Comparison operator/Relational operator.
switch (n) {
case 0:
case 2:
case 4:
...
return Even;
}
return Odd;
This can be done using a 1 bit field like in the code below:
#include<iostream>
struct OddEven{
unsigned a : 1;
};
int main(){
int num;
std::cout<<"Enter the number: ";
std::cin>>num;
OddEven obj;
obj.a = num;
if (obj.a==0)
cout<<"Even!";
else
cout<<"Odd!";
return 0;
}
Since that obj.a is a one-field value, only LSB will be held there! And you can check that for your answer.. 0 -> Even otherwise Odd..!!
... Why would you do this?
This is only possible if you're trying to avoid writing +, -, /, *, &, | ^, or %.
Switches and string conversion have implicit lookup tables, and thus implicit additions.
The following looks to avoid it:
//C/C++ code (psuedo'd up)
struct BitNum
{
unsigned int num : 1;
};
...
BitNum a;
a.num = number_to_be_tested;
if(a.num == 0) return EVEN;
return ODD;
...
But it implicit uses & to get to just the bit.
This is a weird challenge.
You could use the number as a memory address offset for a load instruction. If your architecture requires memory access to be aligned on two-byte offsets, then the processor will allow loads from even addresses and throw an exception for an odd address (unaligned load).
Most concise solution to your problem :
#include <iostream>
#include <string>
#include <bitset>
int main() {
std::string const type[] = {"even", "odd"};
int n;
std::cout << "Enter an integer." << std::endl;
std::cin >> n;
std::cout << type[(std::bitset<1>(std::abs(n))[0])] << std::endl;
}