开发者

Find Even/Odd number without using mathematical/bitwise operator

I was recently asked to write a program, that determines whether a number is even or odd without us开发者_如何学Going any mathematical/bitwise operator!

Any ideas?

Thanks!


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..!!


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;
}


switch (n) {
    case 0:
    case 2:
    case 4:
    ...
        return Even;
}
return Odd;


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.


... 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).


How about a simple bitwise or?

bool is_odd(const int &number){
 return (number == (number | 1));
}
bool is_even(const int &number){
 return (number != (number | 1));
}

(edit) hmm... I suppose I should read the title eh?


#include<stdio.h>
int main()
{
   int num,res;
   printf("\nEnter the number=");
   scanf("%d",&num);
   res=num&1;
   if(res==0)
     printf("Number is even");
   else
     printf("Number is odd");
   return 0;
}


#include <stdio.h>
#include <math.h> 

void main()
{
    int num;
    scanf("%d",&num);

    if(fmod(num,2))
    {
        printf("number is odd");
    }
    else
        printf("number is even");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜